【问题标题】:chrome extension message from background.js to content.js with response, TypeError cannot read property从 background.js 到 content.js 的 chrome 扩展消息带有响应,TypeError 无法读取属性
【发布时间】:2018-04-10 19:38:05
【问题描述】:

您好,我是 chrome 扩展的新手,我正在尝试进行扩展。我希望每次用户转到另一个选项卡时 background.js 向 content.js 发送请求,为此我在 background.js 中有这段代码

chrome.tabs.onActivated.addListener(function() {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      chrome.tabs.sendMessage(tabs[0].id, {greeting: "update"}, function(response) {
          console.log(response.proto);
      });
    });
});

在 content.js 中我有这个代码来接收请求并发送响应:

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        console.log(request.greeting);
        var protocol = window.location.protocol;
        sendResponse({ proto: protocol });
    }
);

我在后台控制台中收到此错误:

Error in event handler for (unknown): TypeError: Cannot read property 'proto' of undefined
    at background.js:6:32

我在普通控制台中没有收到任何错误。我已经使用了这个文档:

https://developer.chrome.com/apps/messaging

https://developer.chrome.com/extensions/tabs#event-onActivated

我做错了什么?

【问题讨论】:

    标签: javascript google-chrome google-chrome-extension


    【解决方案1】:

    content.js 仅在urlmanifest.json 文件中定义的选项卡中运行。如果活动选项卡的url 与这些网址不匹配,则background.js 不匹配。

    【讨论】:

    • 我的 manifest.json 文件中有这个:"content_scripts": [ { "matches": ["<all_urls>"], "js": ["content.js"] } ],
    • 在修改 chrome 扩展后尝试刷新旧标签以加载 content.js@Linus
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    相关资源
    最近更新 更多