javascript - Chrome : Passing data between contentscript and popup. html

标签 javascript google-chrome-extension content-script

我有一个简单的函数,它只是将 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/

相关文章:

javascript - 如何在pixi.js中注入(inject)css文件

python - 如何添加或删除 Chrome 扩展 "after"selenium 网络驱动程序已实例化/定义

javascript - Chrome 将脚本注入(inject)上一个选项卡?

javascript - 通过 Google Chrome 扩展程序中的内容脚本从 DOM 元素中删除 "onmousedown"事件

javascript - PhantomJS 持久 cookies 和 Javascript

javascript - Choropleth map 的 D3 js 工具提示问题

javascript - 编辑 woocommerce Assets 的正确方法是什么?

javascript - 仅当标签具有权限时,才会扩展脚本才会

javascript - Chrome 扩展程序 : How to reload tab from anywhere using keyboard events?

javascript - 在 prefs 初始化之前加载 pref showConsoleLogs,你不会得到正确的结果