首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >chrome.runtime.onMessage不存在

chrome.runtime.onMessage不存在
EN

Stack Overflow用户
提问于 2019-08-30 17:54:12
回答 1查看 1.8K关注 0票数 2

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

popup.js

代码语言:javascript
运行
复制
(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));

background.js

代码语言:javascript
运行
复制
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 -内容脚本

代码语言:javascript
运行
复制
(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));

更新

我已经根据评论中的建议修改了代码。现在,我在后台脚本控制台日志中有一个错误:Error in event handler: TypeError: Error in invocation of tabs.sendMessage(integer tabId, any message, optional object options, optional function responseCallback): No matching signature. chrome.tabs.sendMessage()有什么问题

background.js

代码语言:javascript
运行
复制
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});
    });
  }
});
EN

回答 1

Stack Overflow用户

发布于 2020-08-17 06:38:36

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

发现here的解决方案是使用import import('path/your js file')函数来导入脚本,而不是脚本标记。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57724506

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档