javascript - chrome.runtime.onMessage 不存在

标签 javascript google-chrome google-chrome-extension chrome-native-messaging

我已经 asked为了帮助理解如何正确实现 chrome 扩展的消息 API,然后我在我的代码中实现了它。 工作流程是 popup.js 将向我的后台脚本发送一条消息,让它知道弹出窗口已打开并且可以接收数据,然后后台脚本向将获取所需数据的内容脚本发送一条消息,然后发回这些数据的响应。我在 popup.js 控制台中收到错误消息:Uncaught TypeError: chrome.runtime.onMessage is not a function。我还注意到内容脚本未在消息上触发,是否有任何解决方法,代码有什么问题?

弹窗.js

(function($){
  $(document).ready(function(){
    console.log('Extension Started!');
    chrome.runtime.sendMessage({type:'init_popup_feed'});
      chrome.runtime.onMessage(function(message, sender, response){
        console.log(sender);
        if( message.type == 'feed_data' ){
          console.log(message.data);
        }
      });
  });
}(jQuery));

背景.js

const s = [];
chrome.runtime.onMessage.addListener(function(message, sender, response){
  console.log(sender);
  console.log(message.type);
  if( message.type == 'init_popup_feed' ){
    chrome.runtime.sendMessage({type:'grab_feed'});
  }
  else if( message.type == 's_feed'){
    chrome.runtime.sendMessage({type:'feed_data',data:message.data});
  }
  //chrome.runtime.sendMessage({});
});

main.js - 内容脚本

(function($){
  $(document).ready(function(){
    console.log('Extension Started!');
    const l = [];
    var d;
    chrome.runtime.onMessage.addListener(function(message, sender, response){
      console.log(message.type);
      if( message.type == 'grab_feed' ){
        // ... code stuff here ...
          sendResponse({type:'s_feed',data:l});
          console.log(l);
      }
    });
  });
}(jQuery));

更新

我已经根据评论中的建议修改了代码。现在我在后台脚本控制台日志中有一个错误:事件处理程序中的错误:TypeError:调用 tabs.sendMessage(整数 tabId,任何消息,可选对象选项,可选函数 responseCallback)时出错:没有匹配的签名。 chrome.tabs.sendMessage() 有什么问题?

背景.js

var id;
chrome.runtime.onMessage.addListener(function(message, sender, response){
  console.log(message.type);
  if( message.type == 'extension_started'){
    console.log(sender);
    id = sender.tab.tabId;
  }
  else if( message.type == 'init_popup_feed' ){
    chrome.tabs.sendMessage(id, {type:'grab_stories'}, function(response){
        console.log(response);
        chrome.runtime.sendMessage({type:'stories_feed_data',data:response.data});
    });
  }
});

最佳答案

当我使用 <script type="module"> 从内容脚本加载内容脚本时遇到此错误标签。

找到的解决方案here是使用 import import('path/your js file')函数导入脚本而不是脚本标签。

关于javascript - chrome.runtime.onMessage 不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57724506/

相关文章:

css - Chrome/Safari无法填充Flex父级的100%高度

google-chrome-extension - Google Chrome 扩展程序图标的建议大小

javascript - 如何在呈现页面之前在用户脚本中切换 CSS 文件?

javascript - 单击以使用 javascript 按 id 显示多个元素引用

javascript 以错误的顺序执行

javascript - 如何从 <p>Text&lt;input type="... </p> 中获取 'text'

google-chrome - 在 selenium chromedriver 上运行的远程调试 Internjs

javascript - Chrome 扩展 : iterate through all tabs?

JavaScript 单选按钮 html 网络表单

JavaScript ReferenceError - 运行 npm 测试时 undefined object