I am trying to understand chrome background pages. I managed to get background.js script running after cannibalizing on the of examples and it pops up with an alert box every time a user visits a page. However, when I take the same script and move it to a background.html file, I cannot seem to get the file to execute.
I have updated the the manifest file to a page (instead of script) and the extension loads fine. I have also tried playing around with either having the javascript in a script tag directly in the body or in a function as it is now that is called onload on the body or in the head.
Perhaps I don't understand the concept of what a background.html page is used for in a Chrome extension?
Manifest file:
{
"name": "Testing Extension",
"version": "0.2",
"background": { "pages": ["background.html"] },
"permissions": [
"tabs", "https://mail.google.com/*", "http://*/*, https://*/*"
],
"browser_action": {
"name": "Do some action",
"icons": ["icon.png"]
},
"manifest_version": 2,
"web_accessible_resources": ["injectImage.js", "background.html"]
}
injectImage.js
alert('Got Here');
'use strict';
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.tabs.executeScript(null, {file: "injectImage.js"});
});
chrome.browserAction.setBadgeBackgroundColor({color: [0, 200, 0, 100]});
var i = 0;
window.setInterval(function () {
chrome.browserAction.setBadgeText({text: String(i)});
i++;
}, 10);
background.html
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.8.0.min.js"></script>
<script src="injectImage.js"></script>
</head>
<body>
</body>
</html>
currently this code doesn't seem to do anything other than put an icon in the top right corner.
Background scripts or a background page enable you to monitor and react to events in the browser, such as navigating to a new page, removing a bookmark, or closing a tab. Background scripts or a page are: Persistent – loaded when the extension starts and unloaded when the extension is disabled or uninstalled.
Chrome 10 Now Lets Extensions Run in the Background.
Head to More tools > Extensions. Use the toggle for each extension to turn it off. Restart Chrome and go back to the extensions list. Re-enable the extensions.
Background scripts are the place to put code that needs to maintain long-term state, or perform long-term operations, independently of the lifetime of any particular web pages or browser windows.
OR you can directly define js instead of defining a background page and referencing a script file in it (Inline scripts are not allowed as per Content Security Policy (CSP))
"background": {
"scripts": ["background.js"]
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With