简体   繁体   English

内容和背景之间传递的Chrome扩展程序消息无效

[英]Chrome extension message passing between content and background not working

I am developing a chrome extension, here are the main files: 我正在开发一个chrome扩展,这里是主要文件:

background.js

getPageDimension = function (){
    chrome.tabs.getSelected(null, function(tab) {
        chrome.tabs.sendMessage(tab.id, { message: "DIMENSION" }, function(response){
            if (response != null) {
                console.log(response.x);
                console.log(response.y);
                console.log(response.w);
                console.log(response.h);
            }else{
                console.log('Response is null');
            }
        });
    }); 
};

content.js

chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {        
    if (msg.message && (msg.message == "DIMENSION")) {                          
        var dimension = getPageDiemension(document.documentElement);        
        console.log(dimension.x);
        console.log(dimension.y);
        console.log(dimension.w);
        console.log(dimension.h);
        sendResponse({x: dimension.x, y: dimension.y,w: dimension.w,h: dimension.h});       
    }
});

getPageDiemension = function(currentDom){
    var dimension = new Object();
    dimension.x = 0;
    dimension.y = 0;
    dimension.w = currentDom.scrollWidth;
    dimension.h = currentDom.scrollHeight;
    return dimension;
}

So my aim is to get the full height and width of page loaded in current active tab. 所以我的目标是在当前活动选项卡中加载页面的完整高度和宽度。 When I debug my content script, I get the proper response in my background.js , but if run the script without debugging, I get an undefined response in my background.js . 当我调试我的内容脚本时,我在我的background.js中得到了正确的响应,但是如果在没有调试的情况下运行脚本,我在我的background.js得到一个undefined响应。

Here is the declaration of my cotent.js in my manifest.json file: 这是我的manifest.json文件中我的cotent.js的声明:

"content_scripts": [{
    "all_frames": true,
    "matches": [
        "http://*/*", "https://*/*"
    ],
        "js": ["content.js"]
}],

Kindly help me, where am I going wrong?. 请帮助我,我哪里错了? Let me know if you need any further data. 如果您需要任何进一步的数据,请告诉我。

Issues 问题

There are two little problems in your code, which I found after a wile, since that it looks perfectly working (when it isn't at all). 你的代码中存在两个小问题,我发现它们是在一个诡计之后发现的,因为它看起来非常有效(当它完全没有时)。

  1. You're using the deprecated chrome.tabs.getSelected(...) method, which you should avoid. 您正在使用已弃用的chrome.tabs.getSelected(...)方法,您应该避免使用该方法。 Use chrome.tabs.query({active: true, highlighted: true}, ...) instead. 请改用chrome.tabs.query({active: true, highlighted: true}, ...)
  2. In your chrome.runtime.onMessage listener, in the content script, you are doing some calculations before sending the response: this makes the message channel close before you can send a response, and will result in a null response. chrome.runtime.onMessage侦听器中,在内容脚本中,您在发送响应之前正在进行一些计算:这使得消息通道在您发送响应之前关闭,并且将导致null响应。

    Quoting from the official documentation : 引自官方文件

    This function ( sendResponse ) becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse is called). 当事件侦听器返回时,此函数( sendResponse )变为无效,除非您从事件侦听器返回true以指示您希望异步发送响应(这将使消息通道保持打开到另一端,直到调用sendResponse )。

Solution

Now that you know what the problems are, you can easily replace the old tabs.getSelected() with tabs.query() , and add a return true; 现在你知道有什么问题,你可以很容易地取代旧tabs.getSelected()tabs.query()并添加return true; statement in the handler of the runtime.onMessage event in your content script. 内容脚本中runtime.onMessage事件的处理程序中的语句。 The solution is the following, I also lightened the code a bit. 解决方法如下,我也稍微减轻了代码。

Your background.js : 你的background.js

getPageDimension = function (){
    chrome.tabs.query({active: true, highlighted: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, { message: "DIMENSION" }, function(response){
            if (response !== null) console.log('Response:', response);
            else console.log('Response is null');
        });
    }); 
};

Your content.js : 你的content.js

chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {        
    if (msg.message && (msg.message == "DIMENSION")) {                          
        var dimension = getPageDiemension(document.documentElement); 
        console.log('Dimension:', dimension);
        sendResponse(dimension);       
    }
    return true;
});

getPageDiemension = function(currentDom){
    return { x: 0, y: 0,
        w: currentDom.scrollWidth,
        h: currentDom.scrollHeight
    }
}

Working example 工作实例

You can find a working example I made for testing HERE . 你可以找到我在这里测试的一个工作示例。

Documentation links 文档链接

Just for clarity, I'm leaving you some documentation links regarding the APIs involved in this extension that you may find helpful: 为了清楚起见,我将为您留下一些关于此扩展中涉及的API的文档链接,您可能会发现它们很有帮助:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Chrome扩展程序消息在内容和背景之间传递 - Chrome extension message passing between content and background Chrome 扩展消息在后台和内容脚本之间传递 - Chrome Extension Message Passing between background and content script Chrome扩展程序:无法使消息传递在后台脚本和内容脚本之间正常工作 - Chrome extension: can't get message passing to work between background script and content script Chrome 扩展消息传递不起作用(background.js 到 content.js) - Chrome extension message passing not working (background.js to content.js) 在 chrome 扩展中的后台和内容脚本之间传递消息有困难 - Difficulty passing messages between background and content script in chrome extension 在background和content_script之间打开一个用于chrome扩展的消息端口 - Opening a message port between background and content_script for a chrome extension Chrome扩展程序消息传递不起作用? - Chrome extension message passing is not working? chrome扩展中传递的消息不起作用 - Message passing in chrome extension not working chrome 扩展中的内容脚本和后台页面之间的消息传递无法正常工作 - messaging between content script and background page in a chrome extension is not working as it is supposed to be Chrome扩展程序将消息传递到后台页面 - Chrome extension passing message to background page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM