javascript - Chrome API : sendMessage not receiving properly from content script to background. js

标签 javascript google-chrome google-chrome-extension google-chrome-app sendmessage

<分区>

我正在尝试设置我的 content_script.js 以将消息发送到 background.js。 Background.js 能够接收消息并对其执行操作,但 content_script.js 无法接收/打印它。

content_script.js

chrome.runtime.sendMessage({method: "getSettings"}, function(response) {
    console.log(response.data);
    console.log("This is not printing either");
});

背景.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getSettings") {
        chrome.storage.sync.get(null, function (val) {
            sendResponse({data: "test"});
            console.log("Responding: " + val.radioSettings);
        });
    }
});

background.js 中的 Console.log 打印来自 chrome.storage 的正确消息,但我的 content_script.js 中的 console.log 从不打印。

我觉得这很接近,但只是缺少一些小东西。这是我的 list 的一部分:

list .json

{
  "version": "0.0.1",
  "manifest_version": 2,
  "browser_action": {
    "default_icon": "icons/icon19.png",
    "default_popup": "popup.html"
  },
  "background": {
    "scripts": ["js/background.js"]
  },
  "permissions": [
    "storage",
    "tabs"
  ],
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["js/jquery-1.11.3.min.js", "js/content_script.js"]
    }
  ]
}

最佳答案

那解决了它——感谢重复问题链接。

为了让其他人更容易,这里是另一个答案所说的:

From the documentation for chrome.runtime.onMessage.addListener:

This function 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).

So you just need to add return true; after the [end of addListener] to indicate that you'll call the response function asynchronously.

这是正确的代码版本:

背景.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getSettings") {
        chrome.storage.sync.get(null, function (val) {
            sendResponse({data: "test"});
            console.log("Responding: " + val.radioSettings);
        });
    }
    return true;
});

关于javascript - Chrome API : sendMessage not receiving properly from content script to background. js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33294888/

相关文章:

javascript - 在 React Native 中将嵌套的 if/else 转换为三元数

javascript - Electron 位置。路径名在初始加载时不正确

google-chrome - Google 的 OpenInChrome 未在 iOS 9 中检测或打开 Google Chrome 应用程序

google-chrome-extension - "chrome.storage.sync"是否在云端存储数据?

javascript - 将任意 JS URL 加载到 Chrome 中当前页面的上下文中?

javascript - 为什么 Angular 中的这个变量没有更新?

javascript - 当显示设置为无时显示 div

javascript - Chrome 扩展程序 : dealing with multiple message listeners

http - Chrome - 为什么它发送 if-modified-since 请求?

google-chrome-extension - Chrome 扩展程序错误 : “Unchecked runtime.lastError while running browserAction.setIcon: Icon invalid."