如何将数据从内容脚本传递到popup.html? [英] How to pass data from content script to popup.html?

查看:95
本文介绍了如何将数据从内容脚本传递到popup.html?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm learning how to make chrome extensions. 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. I've read about the message passing in the Chrome documentation but I'm unable to make it work. Can anyone help me?

我的代码:

内容脚本文件:main.js

content script file: 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

popup javascript file: 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));


也许我的代码做错了.

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

I get this errors in the console:

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

// content script console error
Error handling response: TypeError: Cannot read property 'farewell' of undefined

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

//popup.js console error
jQuery.Deferred exception: chrome.runtime.onMessage.addListner is not a function TypeError: chrome.runtime.onMessage.addListner is not a function:

未捕获的TypeError:chrome.runtime.onMessage.addListner不是函数

Uncaught TypeError: chrome.runtime.onMessage.addListner is not a function

更新

我已经设法将消息从内容脚本传递到popup.js,但是我需要一种方法来保留消息,直到用户单击扩展图标.我怎么也可以做到这一点?

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. 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.

鉴于此,最有可能使您的内容脚本将其消息发送到持久背景(默认设置为btw),并用作消息的存储库,直到弹出窗口请求它们为止.

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.

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'}...,然后从弹出窗口中发送

Now from content script, send chrome.runtime.sendMessage({imageURIs: l, type: 'from_content_script'}... and from the popup send

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"没有任何意义;他们只是为了清楚起见.

Of course the strings 'from_popup' and 'from_content_script' mean nothing; they are just there for clarity.

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

If you need the popup to initiate the flow, you will need to:

  • 从弹出窗口发送消息
  • 在后台将消息发送到内容脚本
  • 应该对背景做出反应
  • 应该对弹出窗口做出反应

这篇关于如何将数据从内容脚本传递到popup.html?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆