Reputation: 172
After scouring SO, the Google Chrome Developer docs, and other websites... I'm still having a problem getting my content script to auto-start. Essentially, I need the content script to poll for div innerHtml every x seconds and send a message to the background.js script for further processing. Seems simple enough, but even with "run_at":"document_end" specified, it never starts. I suspect it's something trivial so I'm just looking for other sets of eyes to point me in the right direction. Also, it needs to run with no user interaction at all.
Here's my manifest.json file:
{
"name": "My Extension Name",
"description": "Extension description",
"version": "1.0",
"background": {
"scripts": ["bg.js"]
},
"icons": {
"16": "icon16.png",
"48": "icon48.png",
"128": "icon128.png"
},
"permissions": [
"tabs",
"http://*/*",
"https://*/*"
],
"content_scripts": [{
"matches": ["http://*/*", "https://*/*"],
"js": ["content.js"],
"run_at": "document_start",
}],
"manifest_version": 2
}
my content.js file:
var pollInterval = 30000;
var timerId;
function startPoller() {
var elementOfInterest = document.getElementById('id_of_interest');
var content = elementOfInterest.innerHtml;
chrome.runtime.sendMessage({payload: content});
timerId = window.setTimeout(startPoller, pollInterval);
}
document.addEventListener('DOMContentLoaded', function () {
startPoller();
});
and the bg.js file:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(JSON.stringify(request));
}
);
so it's pretty uninteresting. Help appreciated.
Upvotes: 0
Views: 2915
Reputation: 172
The working code is below:
manifest.json file:
{
"name": "My Extension Name",
"description": "Extension description",
"version": "1.0",
"background": {
"scripts": ["bg.js"]
},
"icons": {
"16": "icon16.png",
"48": "icon48.png",
"128": "icon128.png"
},
"permissions": [
"tabs",
"http://*/*",
"https://*/*"
],
"content_scripts": [{
"matches": ["http://*/*", "https://*/*"],
"js": ["content.js"],
"run_at": "document_start",
}],
"manifest_version": 2
}
content.js file:
var pollInterval = 5000;
var timerId;
function startPoller() {
try {
console.log('startPoller called');
var elementOfInterest = document.getElementById('nav_home');
if (elementOfInterest !== undefined && elementOfInterest !== null) {
var content = elementOfInterest.innerHTML;
chrome.runtime.sendMessage({payload: content});
}
} catch (error) {
console.log(error);
}
timerId = window.setTimeout(startPoller, pollInterval);
}
window.addEventListener('DOMContentLoaded', function () {
console.log('window.addEventListener');
startPoller();
});
bg.js file:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(JSON.stringify(request));
}
);
Thanks for your eyeballs, folks
Upvotes: 2