Chrome: Passing data between contentscript and popup.html
-
14-11-2019 - |
質問
I've got a simple function that just passes location.href
from contentscript to the popup.html page. It's not working. what I've got is..
in popup.html..
chrome.tabs.getSelected(null,function(tab)
{
chrome.tabs.sendRequest({req: "getlocation"}, function(response){
return response.reply;
});
});
in my contentscript...
case "getlocation":
sendResponse({
reply: location.href
});
break;
Why isn't my code working?
解決
Some params are missing, plus you can't use return
from an async callback function.
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;
}
});
他のヒント
sendRequest is outdated.
use sendMessage
所属していません StackOverflow