簡體   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