我正在尝试构建一个Chrome扩展程序,该扩展程序将在Deezer的相册页面上添加一个按钮。
我的清单如下:
{
"manifest_version": 2,
"name": "Deezeet",
"description": ".",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["https://www.deezer.com/*", "http://www.deezer.com/*"],
"js": ["jquery.js", "popup.js"],
"run_at": "document_end"
}
],
"web_accessible_resources": ["script.js"],
"permissions": [
"tabs", "http://*/*", "https://*/*"
],
"content_security_policy": "script-src 'self' https://api.deezer.com; object-src 'self' https://api.deezer.com; script-src 'self'"
}
我的popup.js(从此处开始):
var s = document.createElement('script');
s.src = chrome.extension.getURL('script.js');
s.onload = function() {
this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s);
还有我的script.js(现在仅用于测试):
$('header').hide();
但这是行不通的。我所有的JS都在弹出窗口中运行。我能做些什么?
您正在打开一个弹出窗口,并在弹出窗口中看到效果:
[...]即使我使用alert('bam')或类似的东西,它们也都在我的弹出窗口中运行。
当您打开它时,它与任何其他页面无关。您已将脚本设置为内容脚本。当您导航到页面或刷新现有页面时,它将执行。
如果您需要在单击扩展按钮时触发脚本,则应default_popup
从清单中删除该属性,添加一个后台脚本,然后在其中添加一个单击处理程序:
chrome.browserAction.onClicked.addListener(function(tab){
chrome.tabs.executeScript(tab.id, {file: "popup.js"});
// Or, alternatively, send a message to an already-injected script
});
请注意:将脚本作为<script>
元素注入是一种非常繁琐的解决方案,仅需逃避孤立的上下文。在您的测试案例中,您仅访问页面的DOM,popup.js
而不需要包装器。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句