Chrome扩展程序:在浏览器操作中,创建一个弹出窗口并执行脚本 [英] Chrome Extension: On browser action, create a pop up and execute a script
问题描述
我正在构建一个Chrome扩展程序,并希望在用户单击Chrome中的浏览器操作图标时显示弹出窗口并运行脚本.
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.
我可以通过在manifest.json中放置'"default_popup":"popup.html"'来使弹出窗口发生.但是,当我这样做时,background.js似乎没有运行.当我删除'"default_popup":"popup.html"'时,background.js似乎正在运行.
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.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
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
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);
推荐答案
在弹出页面时,不能使用 onClicked
方法. Google文档.
You can't use the onClicked
method when you have a popup page. Google docs.
onClicked:单击浏览器操作图标时触发.此事件不会触发如果浏览器操作有弹出窗口.
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.
这篇关于Chrome扩展程序:在浏览器操作中,创建一个弹出窗口并执行脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!