我正在尝试编写一个非常简单的 Chrome 扩展程序。此时只有一个弹出式 html 文件,它会在单击浏览器操作图标时尝试显示警报。我显然做错了什么,因为警报没有触发。
list .json
{
"name": "Simple",
"description": "Simple",
"version": "1.0",
"browser_action": {
"default_title": "Simple",
"default_icon": "images/icon.png",
"default_popup": "popup.html"
},
"manifest_version": 2
}
弹出窗口
<html>
<head>
<script>
//Executed when the extension's icon is clicked
chrome.browserAction.onClicked.addListener(function(tab)
{
alert("gah");
});
</script>
</head>
<body>
Hello World!
</body>
</html>
我也试过:
<html>
<head>
<script>
function onPageLoad()
{
//Executed when the extension's icon is clicked
chrome.browserAction.onClicked.addListener(function(tab)
{
alert("gah");
});
}
</script>
</head>
<body onload="onPageLoad()">
Hello World!
</body>
</html>
根据响应更新 感谢您的答复。我进行了以下更改,但仍未被调用 browser.Action.onClicked() (您可以看到我使用的是 console.log() 而不是警报。(显示全局范围内的日志,内部的日志回调不是)。
list .json
{
"name": "Simple",
"description": "Simple",
"version": "1.0",
"permissions": ["tabs", "http://*/*", "https://*/*"],
"background": {
"persistent": false,
"scripts": ["popup.js"]
},
"browser_action": {
"default_title": "Simple",
"default_icon": "images/icon.png",
"default_popup": "popup.html"
},
"manifest_version": 2
}
弹出窗口
<html>
<head>
<script type="text/javascript" src="popup.js"></script>
</head>
<body>
<div style="white-space: nowrap">
Hello World!
</div>
</body>
</html>
弹出窗口
console.log("Running at global scope")
//Executed when the extension's icon is clicked
chrome.browserAction.onClicked.addListener(function(tab)
{
console.log("Running insode of addListener()");
});
最佳答案
chrome.browserAction.onClicked
不能在弹出窗口中使用。这没有多大意义——您在点击浏览器操作图标后开始监听它是否被点击。可以再次单击它,但弹出窗口将关闭,监听器将在任何事情发生之前终止。
chrome.browserAction.onClicked
应该在后台页面上使用,并且仅当不使用浏览器操作的弹出窗口时:
This event will not fire if the browser action has a popup.
你应该只写:
<script>
alert("gah");
</script>
但我不确定警报是否在弹出窗口中有效。最好尝试类似的方法:
<script>
document.getElementsByTagName('body')[0].innerHTML = "gah";
</script>
编辑
还有一件事需要在您的扩展中修复。正如@Cody 在他的回答中所建议的那样,您不应该使用内联脚本。出于安全原因,它被阻止。将我上面建议的代码放入一个单独的 javascript 文件中,然后将其包含在 popup.html
head:
<script src='script.js' type='text/javascript'></script>
关于javascript - Chrome 扩展程序 : browserAction. onClicked.addListener() 未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12706649/