问题
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);
回答1:
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.
回答2:
Try this,
chrome.browserAction.onClicked.addListener((tabs) => {
chrome.tabs.executeScript(null,{file:"popup.js"})
})
Now when user clicks on a browser action icon, will execute the file popup.js
来源:https://stackoverflow.com/questions/25733511/chrome-extension-on-browser-action-create-a-pop-up-and-execute-a-script