Chrome 扩展 - Background.html sendResponse 到内容脚本

发布于 2024-11-05 07:14:56 字数 1494 浏览 0 评论 0原文

我在 Stockoverflow 上读过无数的答案,但似乎没有一个能帮助我回答我的问题。基本上,这是我的代码:

Background.html

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {

    if (request.method == "getIP") {

        var req = new XMLHttpRequest();
        var domain
        var ip = "bla";

        chrome.tabs.getSelected(null,function(tab) {
            domain = tab.url;
            domainSplit = domain.match(/^[\w-]+:\/*\[?([\w\.:-]+)\]?(?::\d+)?/)[1];

            req.open (
                    "GET",
                    "http://colourpad.co.uk/projects/dub3helper/ip.php?" + domainSplit,
                    true);
                req.onreadystatechange = getIP;
                req.send(null);

                function getIP() {
                    if(req.readyState == 4) {
                        var ip = req.responseText;
                        alert (ip);
                        sendResponse({domainToIP: "Tester " + ip });    
                    }   
                }
            });             
        }
    else {
        sendResponse({}); //Snub them
    }

});

内容脚本

chrome.extension.sendRequest({method: "getIP"}, function(response) {
    $("p#versionNumber").append("<span>: " + response.domainToIP + "</span>");
});

脚本的基础工作正常,即它确实将 ip 作为警报 (ip) 返回;确实会使用正确的 ip 数据触发。问题似乎是将 ip 变量发送到我的内容脚本。我认为这可能是一个简单的情况,将 sendResponse 放在错误的位置,但我现在真的不明白为什么。我是 Chrome 扩展开发的新手。

非常欢迎任何帮助,这让我发疯!

I've read countless answers here at Stockoverflow but none seem to be help me answer my question. Basically, here's my code:

Background.html

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {

    if (request.method == "getIP") {

        var req = new XMLHttpRequest();
        var domain
        var ip = "bla";

        chrome.tabs.getSelected(null,function(tab) {
            domain = tab.url;
            domainSplit = domain.match(/^[\w-]+:\/*\[?([\w\.:-]+)\]?(?::\d+)?/)[1];

            req.open (
                    "GET",
                    "http://colourpad.co.uk/projects/dub3helper/ip.php?" + domainSplit,
                    true);
                req.onreadystatechange = getIP;
                req.send(null);

                function getIP() {
                    if(req.readyState == 4) {
                        var ip = req.responseText;
                        alert (ip);
                        sendResponse({domainToIP: "Tester " + ip });    
                    }   
                }
            });             
        }
    else {
        sendResponse({}); //Snub them
    }

});

Content script

chrome.extension.sendRequest({method: "getIP"}, function(response) {
    $("p#versionNumber").append("<span>: " + response.domainToIP + "</span>");
});

The basics of the script work correctly, i.e. it does bring back the ip as the alert (ip); does fire with the correct ip data. The issue seems to be sending the ip variable to my content script. I think it may be a simple case of placing the sendResponse in the wrong place, but I really can't see why at the moment. I'm new to chrome extension development.

Any help is massively welcome, its driving me mad!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

权谋诡计 2024-11-12 07:14:57

你的例子对我来说效果很好。也许您正在收到响应,但您的内容脚本没有显示它?尝试用console.log(response)代替那个jquery,并检查控制台的内容脚本和背景页面,也许有一些错误。

关于您的背景页面的一些建议:

而不是:

chrome.tabs.getSelected(null,function(tab) {
    domain = tab.url;
    ...
});

您可以使用:

domain = sender.tab.url;

而不是:

req.onreadystatechange = getIP;
function getIP() {
    ...
}

尝试:

req.onreadystatechange = function() {
    ...
}

更新:

尝试关闭:

req.onreadystatechange = (function(sendResponse) {
    return function () {
      if(req.readyState == 4) {
          ... 
      }   
  }
})(sendResponse);

Your example worked fine for me. Maybe you are receiving response but your content script doesn't display it? Try console.log(response) instead of that jquery, and check console for both content script and background page, maybe there are some errors.

Couple suggestions about your background page:

Instead of:

chrome.tabs.getSelected(null,function(tab) {
    domain = tab.url;
    ...
});

You can use:

domain = sender.tab.url;

Instead of:

req.onreadystatechange = getIP;
function getIP() {
    ...
}

Try:

req.onreadystatechange = function() {
    ...
}

Update:

Try closure:

req.onreadystatechange = (function(sendResponse) {
    return function () {
      if(req.readyState == 4) {
          ... 
      }   
  }
})(sendResponse);
攒一口袋星星 2024-11-12 07:14:57

似乎代码与 background.html 页面上使用的另一个 onRequest.addListener 发生冲突。通过将两个单独的侦听器合并为一个由 switch case 分隔的侦听器解决了该问题:

chrome.extension.onRequest.addListener(
    function(request, sender, sendResponse)
    {
        switch (request.name)
        {
            case "getPreferences":
            // request from the content script to get the preferences.
            sendResponse(
                {
                    Bla : localStorage["bla"]
                });
            break;
            case "getIP":
            // Convert Domain to IP
                var req = new XMLHttpRequest();
                var domain
                var ip = "bla";

                domain = sender.tab.url;
                domainSplit = domain.match(/^[\w-]+:\/*\[?([\w\.:-]+)\]?(?::\d+)?/)[1];

                req.open (
                        "GET",
                        "http://colourpad.co.uk/projects/dub3helper/ip.php?" + domainSplit,
                        true);
                    req.onreadystatechange = function() {
                        if(req.readyState == 4) {
                            var ip = req.responseText;
                            sendResponse({domainToIP: ip });    
                        }   
                    }
                    req.send(null);
            break;
            default:
            sendResponse({});
        }
    }
);

Seems the code was conflicted with another onRequest.addListener used on the background.html page. Fixed the issue by merging both separate listeners into one separated by a switch case:

chrome.extension.onRequest.addListener(
    function(request, sender, sendResponse)
    {
        switch (request.name)
        {
            case "getPreferences":
            // request from the content script to get the preferences.
            sendResponse(
                {
                    Bla : localStorage["bla"]
                });
            break;
            case "getIP":
            // Convert Domain to IP
                var req = new XMLHttpRequest();
                var domain
                var ip = "bla";

                domain = sender.tab.url;
                domainSplit = domain.match(/^[\w-]+:\/*\[?([\w\.:-]+)\]?(?::\d+)?/)[1];

                req.open (
                        "GET",
                        "http://colourpad.co.uk/projects/dub3helper/ip.php?" + domainSplit,
                        true);
                    req.onreadystatechange = function() {
                        if(req.readyState == 4) {
                            var ip = req.responseText;
                            sendResponse({domainToIP: ip });    
                        }   
                    }
                    req.send(null);
            break;
            default:
            sendResponse({});
        }
    }
);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文