【发布时间】:2012-12-15 18:37:08
【问题描述】:
我正在尝试获取弹出/弹出菜单以根据当前页面 URL 向用户显示不同的内容,但无法获得连接。我读过只有 background.html 可以访问 Chrome 框架中的 current-tabs 的 URL,所以我试图让它通过它告诉我的 content-script 和我的 popup.js消息传递—— background.html 将收到一条消息,并将在响应中包含正确的信息。弹出窗口应该能够使用 getBackgroundPage() 但内容注入脚本是不允许的,所以我想同时使用消息传递并有一个通用的解决方案。
所以...关于失败连接的控制台消息被隐藏在一些我什至无法查看的随机实现代码中,即: miscellaneous_bindings:236 或 miscellaneous_bindings:235,具体取决于 cal 的参数。试图查看我们击中的位置让我明白:
位于 chrome-devtools://devtools/miscellaneous_bindings 的网页可能暂时关闭或永久移动到新网址。
我确信我在做一些愚蠢的事情,否则我的系统出了问题,但我不知道是哪一个。我看到的大多数示例和问题要么需要 beta 发布通道功能,要么使用 v1.0 清单,使用不推荐使用的功能(来自 2011 年的问题),或者没有接受的答案。我用 Chrome 24.0.1312.40 m 而且我已经禁用了其他扩展。
这是我们的设置方式...
popup.html
<!doctype html>
<html>
<head>
<title>Working title popup</title>
<script src="popup.js">
// nothing allowed in here
</script>
</head>
<body>
<form>
<fieldset>
<button>Demo</button>
<!--^ push to try again to get response string from background -->
</fieldset>
</form>
</body>
</html>
popup.js:
asky();
function asky(){
catchersMit=null;
console.log("Going to get info.");
// Below causing Port error:
//"Could not establish connection. Receiving end does not exist.":
chrome.extension.sendMessage({msg:"need some info"} //arg1
,function(response){ //arg2
alert(reponse.msg);
//^ yields undefined in alert window
catchersMit=response;}
);
//_*_ catchersMit still appears undefined out here.
}
background.html:
<!doctype html>
<html><head><script type="text/javascript">
chrome.extension.onMessage.addListener(
function(message,sender,sendResponse){
sendResponse( {msg: "info you wanted"} );
} // anonymous (1st parameter) function OUT
); // onRequest listener OUT
</script></head><body></body></html>
manifest.json:
{
"name": "Extension Working Title",
"version": "1.0",
"manifest_version": 2,
"description": "Coolest functionality.",
"browser_action": {
"default_icon": "lnr_icon.png",
"default_popup": "popup.html"
},
"permissions": [ "tabs","http://*/*" ],
"background": { "page": "background.html" }
}
现在我只是在使用 popup.js,因为我发现它更容易调试,但如果我没记错的话,这个问题的解决方案与内容脚本应该没有什么不同。
【问题讨论】:
-
I've read that only background.html has access to current-tabs' URLs in the Chrome framework,假设在所有扩展页面上调用 chrome.tabs() API 产生预期结果是错误的 -
1. CSP 在 background.html 中强制执行 no-inline-scripts 规则 2. 你没有绑定任何
chrome.extension.onMessage监听器。 -
@RobW - 1. 如果我在 popup.html 中包含
<head><script>/*code*/</script>而不是使用<script src="_pathToSrc_">,则会出现导入错误,但在 上没有此类通知b>background.html。那么,只是缺乏执法吗? 2. 在 background.html 我有chrome.extension.onMessage.addListener(//...我需要其他东西来完成绑定吗? -
@dooozies 1. 你应该收到一个错误。不过,您的错误是不寻常的,通常您会收到有关端口的错误。该问题是否也出现在新的 Chrome 配置文件中?
标签: google-chrome google-chrome-extension chromium message-passing