简体   繁体   English

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

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

I'm learning how to make chrome extensions.我正在学习如何制作 chrome 扩展。 I have a content script that will obtain some data and I want to pass them to the popup.html page to display them on the popup DOM.我有一个将获取一些数据的内容脚本,我想将它们传递给 popup.html 页面以在弹出 DOM 上显示它们。 I've read about the message passing in the Chrome documentation but I'm unable to make it work.我已阅读 Chrome 文档中传递的消息,但无法使其正常工作。 Can anyone help me?谁能帮我?

My code:我的代码:

content script file: main.js内容脚本文件: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));

popup javascript file: popup.js弹出 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));


Maybe I'm doing something wrong with the code.也许我在代码上做错了什么。

I get this errors in the console:我在控制台中收到此错误:

// content script console error // 内容脚本控制台错误
Error handling response: TypeError: Cannot read property 'farewell' of undefined错误处理响应:TypeError:无法读取未定义的属性“告别”

//popup.js console error //popup.js 控制台错误
jQuery.Deferred exception: chrome.runtime.onMessage.addListner is not a function TypeError: chrome.runtime.onMessage.addListner is not a function: jQuery.Deferred 异常:chrome.runtime.onMessage.addListner 不是函数 TypeError:chrome.runtime.onMessage.addListner 不是函数:

Uncaught TypeError: chrome.runtime.onMessage.addListner is not a function未捕获的类型错误:chrome.runtime.onMessage.addListner 不是函数

UPDATE更新

I've managed how to pass the message from the content script to the popup.js but I need a way to hold the message until the user click on the extension icon.我已经设法将消息从内容脚本传递到 popup.js,但我需要一种方法来保存消息,直到用户单击扩展图标。 How can I achieve also this?我怎样才能做到这一点?

In general, it will not work to send a message from a content script to a popup unless you know the popup is open: the popup does not exist until you open it.通常,除非您知道弹出窗口已打开,否则将消息从内容脚本发送到弹出窗口是行不通的:直到您打开弹出窗口才存在。

Given this, it will likely be most decoupled to have your content script send its message to a persistent background (which is the default btw) and serve as the repository for your messages until the popup requests them.鉴于此,让您的内容脚本将其消息发送到持久性后台(这是默认的 btw)并作为您的消息的存储库,直到弹出请求它们为止,这可能是最解耦的。

background.js背景.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);
  }
});

Now from content script, send chrome.runtime.sendMessage({imageURIs: l, type: 'from_content_script'}... and from the popup send现在从内容脚本发送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).
});

Of course the strings 'from_popup' and 'from_content_script' mean nothing;当然,字符串 'from_popup' 和 'from_content_script' 没有任何意义; they are just there for clarity.它们只是为了清楚起见。

If you need the popup to initiate the flow, you will need to:如果您需要弹出窗口来启动流程,则需要:

  • send a message from the popup从弹出窗口发送消息
  • to the background, to send a message to the content scripts到后台,向内容脚本发送消息
  • which should respond to the background这应该响应背景
  • which should respond to the popup应该响应弹出窗口

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

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

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