繁体   English   中英

如何将数据从内容脚本传递到 popup.html?

[英]How to pass data from content script to popup.html?

我正在学习如何制作 chrome 扩展。 我有一个将获取一些数据的内容脚本,我想将它们传递给 popup.html 页面以在弹出 DOM 上显示它们。 我已阅读 Chrome 文档中传递的消息,但无法使其正常工作。 谁能帮我?

我的代码:

内容脚本文件:main.js

(function($){
  $(document).ready(function(){
    console.log('Extension Started!');
    var el = $(document).find('#stories_tray');
      var child = el.find('._827c');
        $.each(child, function(i){
          var div = $(child[i])
            .find('._7h4p')
            .attr('data-onkeypress');
          var d = JSON.parse(div);
          if( typeof d[0].a != 'undefined' ){
            console.log(d[0].a[0].preloadImageURIs[0]);
            var l = d[0].a[0].preloadImageURIs[0];

            chrome.runtime.sendMessage({imageURIs: l}, function(response) {
              console.log(response.farewell);
            });
          }
        });
  });
}(jQuery));

弹出 javascript 文件:popup.js

// window.onload = function(){
//   $('.spinner-grow').delay('300')
//     .css({'transition':'ease-out','display':'none'});
// }

(function($){
  $(document).ready(function(){
    console.log('Extension Started!');
    chrome.runtime.onMessage.addListner(function(request, sender, sendResponse){
      console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension");
      console.log(request.imageURIs);
      sendResponse({farwell: "ok"});
    });
  });
}(jQuery));


也许我在代码上做错了什么。

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

// 内容脚本控制台错误
错误处理响应:TypeError:无法读取未定义的属性“告别”

//popup.js 控制台错误
jQuery.Deferred 异常:chrome.runtime.onMessage.addListner 不是函数 TypeError:chrome.runtime.onMessage.addListner 不是函数:

未捕获的类型错误:chrome.runtime.onMessage.addListner 不是函数

更新

我已经设法将消息从内容脚本传递到 popup.js,但我需要一种方法来保存消息,直到用户单击扩展图标。 我怎样才能做到这一点?

通常,除非您知道弹出窗口已打开,否则将消息从内容脚本发送到弹出窗口是行不通的:直到您打开弹出窗口才存在。

鉴于此,让您的内容脚本将其消息发送到持久性后台(这是默认的 btw)并作为您的消息的存储库,直到弹出请求它们为止,这可能是最解耦的。

背景.js

const messageQueue = [];
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  // Arbitrary string allowing the background to distinguish
  // message types. You might also be able to determine this
  // from the `sender`.
  if (message.type === 'from_content_script') {
    messageQueue.push(message);
  } else if (message.type === 'from_popup') {
    sendResponse(messageQueue);
  }
});

现在从内容脚本发送chrome.runtime.sendMessage({imageURIs: l, type: 'from_content_script'}...并从弹出窗口发送

chrome.runtime.sendMessage({type: 'from_popup'}, (response) => {
  // do stuff with response (which will be the value of messageQueue
  // sent from background.js).
});

当然,字符串 'from_popup' 和 'from_content_script' 没有任何意义; 它们只是为了清楚起见。

如果您需要弹出窗口来启动流程,则需要:

  • 从弹出窗口发送消息
  • 到后台,向内容脚本发送消息
  • 这应该响应背景
  • 应该响应弹出窗口

Chrome 运行时没有 onMessage 方法请看这个链接,希望这能帮助你

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM