【发布时间】:2017-10-22 01:50:33
【问题描述】:
我正在尝试创建一个具有侧面板的扩展程序。此侧面板将包含可根据主机页面状态执行操作的按钮。
我跟着this example 注入了侧面板,我可以连接一个按钮 onClick 监听器。但是,我无法访问全局 js 变量。在开发人员控制台中,在主机页面的范围内,我能够看到我所追求的变量(变量名称 - 配置)。但是当我进入侧面板 (popup.html) 的上下文时,我收到以下错误 -
VM523:1 未捕获的 ReferenceError:未定义配置。似乎 popup.html 也在单独的线程中运行。
如何访问按钮的 onClick 处理程序的全局 js 变量?
我的代码:
manifest.json
{
"manifest_version": 2,
"name": "Hello World",
"description": "This extension to test html injection",
"version": "1.0",
"content_scripts": [{
"run_at": "document_end",
"matches": [
"https://*/*",
"http://*/*"
],
"js": ["content-script.js"]
}],
"browser_action": {
"default_icon": "icon.png"
},
"background": {
"scripts":["background.js"]
},
"permissions": [
"activeTab"
],
"web_accessible_resources": [
"popup.html",
"popup.js"
]
}
background.js
chrome.browserAction.onClicked.addListener(function(){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id,"toggle");
})
});
content-script.js
chrome.runtime.onMessage.addListener(function(msg, sender){
if(msg == "toggle"){
toggle();
}
})
var iframe = document.createElement('iframe');
iframe.style.background = "green";
iframe.style.height = "100%";
iframe.style.width = "0px";
iframe.style.position = "fixed";
iframe.style.top = "0px";
iframe.style.right = "0px";
iframe.style.zIndex = "9000000000000000000";
iframe.frameBorder = "none";
iframe.src = chrome.extension.getURL("popup.html")
document.body.appendChild(iframe);
function toggle(){
if(iframe.style.width == "0px"){
iframe.style.width="400px";
}
else{
iframe.style.width="0px";
}
}
popup.html
<head>
<script src="popup.js"> </script>
</head>
<body>
<h1>Hello World</h1>
<button name="toggle" id="toggle" >on</button>
</body>
popup.js
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("toggle").addEventListener("click", handler);
});
function handler() {
console.log("Hello");
console.log(config);
}
【问题讨论】:
-
我无权访问主机页面。主机页面不将其存储在 chrome.storage.local
-
扩展JS无法与页面JS交互。他们在文档中告诉你。
-
@wOxxOm 感谢您的链接。我遇到过,但有些人对此感到困惑。你能帮我理解吗。我必须注入另一个脚本来提取 JS 变量并发送消息?
-
或者我应该将此脚本注入内容脚本并以不同的方式连接 onClick 侦听器?
-
好的,谢谢,如何从按钮调用该脚本?