【发布时间】:2013-09-09 08:45:57
【问题描述】:
在 Chrome 扩展程序中从 popup.js 向 background.js 发送消息(并获得响应)的正确方法是什么?我尝试的每种方法都会出现以下错误:
“端口:无法建立连接。接收端不存在。”
我更愿意使用 chrome.extension.sendMessage() 而不是 chrome.extension.connect() 和 port.postMessage(),但是这两种方法似乎都不起作用。
我想要做的是在 popup.html 中连接一个按钮来调用 popup.js 中的一些 javascript,这些 javascript 回调到 background.js 以获取有关 topMost 的 currentTab() 的信息(即:获取当前 URL 字符串以显示在 popup.html 中)
现在在 popup.js 中(连接到按钮的操作)我有:
function getURL()
{
chrome.extension.sendMessage({greeting: "GetURL"},
function(response) { tabURL = response.navURL });
$("#tabURL").text(tabURL);
}
在 background.js 我有:
chrome.extension.onMessage.addListener( function(request,sender,sendResponse)
{
if( request.greeting == "GetURL" )
{
var tabURL = "Not set yet";
chrome.tabs.getCurrent(function(tab){
tabURL = tab.url;
});
sendResponse( {navURL:tabURL} );
}
}
有什么想法吗?
【问题讨论】:
标签: google-chrome google-chrome-extension