Chrome Extension: On browser action, create a pop up and execute a script
20,465
You can't use the onClicked
method when you have a popup page. Google docs.
onClicked: Fired when a browser action icon is clicked. This event will not fire if the browser action has a popup.
If you want to keep both consider writing a content script.
Author by
Corbin Page
Updated on January 10, 2021Comments
-
Corbin Page over 3 years
I'm building a Chrome extension and would like to show a pop up and run a script when the user clicks on a browser action icon in Chrome.
I can get the popup to occur by putting '"default_popup": "popup.html"' in manifest.json. However, when I do, background.js doesn't seem to run. When I remove '"default_popup": "popup.html"', background.js seems to run.
How can I get both the popup to appear and the script to run?
manifest.json
{ "manifest_version": 2, "name": "Typo Blaster", "description": "Blast away typos and make the internet a safer place for the kids.", "version": "0.1", "browser_action": { "default_icon": "icon.png", "default_title": "Blast the typo!", "default_popup": "popup.html" }, "permissions": [ "activeTab" ], "background": { "scripts": ["background.js"], "persistent": false }, "icons": { "16": "icon16.png", "48": "icon48.png", "128": "icon128.png" } }
popup.html
<!doctype html> <html> <head> <title>Typo Blaster</title> <style> body { min-width: 357px; overflow-x: hidden; } img { margin: 5px; border: 2px solid black; vertical-align: middle; width: 75px; height: 75px; } </style> <script src="popup.js"></script> </head> <body> <h1>Got it!</h1> </body> </html>
background.js
chrome.browserAction.onClicked.addListener(function(tab) { // No tabs or host permissions needed! console.log('Turning ' + tab.url + ' red!'); chrome.tabs.executeScript({ code: 'document.body.style.backgroundColor="red"' }); }); alert('hello ' + document.location.href);
-
Corbin Page over 9 yearsThanks for the explanations and the links. Makes sense to me. I'm going to use a content script instead.
-
Xan over 9 yearsNote: this is another possible solution. You'll keep the background script and the popup.