我有一个简单的函数,它只是将 location.href
从 contentscript 传递到 popup.html 页面。它不工作。我得到的是..
在 popup.html..
chrome.tabs.getSelected(null,function(tab)
{
chrome.tabs.sendRequest({req: "getlocation"}, function(response){
return response.reply;
});
});
在我的内容脚本中...
case "getlocation":
sendResponse({
reply: location.href
});
break;
为什么我的代码不起作用?
最佳答案
缺少一些参数,而且您不能在异步回调函数中使用 return
。
popup.html:
function getCurrentUrl(callback){
chrome.tabs.getSelected(null,function(tab){
chrome.tabs.sendRequest(tab.id, {req: "getlocation"}, function(response){
callback(response.reply);
});
});
}
getCurrentUrl(function(url){
console.log("url:", url);
});
content_script.js:
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
switch(request.req) {
case "getlocation":
sendResponse({
reply: window.location.href
});
break;
}
});
关于javascript - Chrome : Passing data between contentscript and popup. html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5017850/