【问题标题】:How do I send an array from a content script to a popup script如何将数组从内容脚本发送到弹出脚本
【发布时间】:2019-06-10 19:53:31
【问题描述】:

我正在尝试将页面上所有链接的数组发送到我的 chrome 扩展程序。我正在使用内容脚本抓取数组数据并使用消息将数据发送到扩展程序,不幸的是,在收到来自内容脚本的消息后,数组的数据不完整。

我正在使用 sendMessage 函数来注入我的内容脚本,该脚本然后收集页面信息(页面的 url 和页面上的链接),然后通过消息发送。

这个消息然后被popup.js中的监听器接收,然后信息被存储在一个对象中,不幸的是信息不完整。

//Manifest.json
{
    "name": "PHD SEO Tools Test",
    "version": "1.0",
    "description": "SEO Tools Browser Extension First Draft",
    "permissions": [
        "tabs", 
        "activeTab",
        "storage"
    ],
    "background": {
        "scripts": ["background.js"],
        "persistent": false
    },
    "browser_action": {
        "default_popup": "popup.html"
    },
      "options_page": "options.html",
    "manifest_version": 2
}
//ContentScript.js
//Store page information in an object
let pageInfo = {
    currentPageURL: window.location.href,
    links: []
}

//Grab all links on the page
links = document.getElementsByTagName("link");
//Grab URL for each link
for (i = 0; i < links.length; i++) {
    //Push url to pageInfo object
    pageInfo.links.push(links[i]);
}

//Send a message containing the pageInfo properties 
chrome.runtime.sendMessage({
    //To add data to the message payload add another property below
    url: pageInfo.currentPageURL, 
    links: pageInfo.links
}, response => {
    console.log(response);
})
//Popup.js
//Variable to store recieved messages
let pageInfo = {
    currentPageURL: '',
    links: []
}

//Variable to store popup UI components
let ui = {
    popup: document.getElementById("main"),
    displayUrlButton: document.getElementById("displayUrlButton"),
    displayUrl: document.getElementById("displayUrl")
}

//Recieve message from background using the following notation:
//request.url
//request.links
chrome.runtime.onMessage.addListener(
    (request, sender, sendResponse) => {
        console.log(request)
        pageInfo.currentPageURL = request.url;
        pageInfo.links = request.links;
        sendResponse({message: "info recieved by popup"});
    }
);

ui.displayUrlButton.addEventListener('click', () => {
    //If ui.displayUrl is empty
    if(ui.displayUrl.childNodes.length < 2) {
        //create a h2 element
        let urlText = document.createElement("h2");
        //set the content of the h2 element
        urlText.innerHTML = "Current page: " + pageInfo.currentPageURL;
        //Add h2 element to page
        ui.displayUrl.appendChild(urlText);
    }
})

function sendMessage() {
//Query tabs for the active tab in the current window
chrome.tabs.query({active: true, currentWindow: true}, tabs => {
    //Execute a script on the active tab
    chrome.tabs.executeScript(tabs[0].id, {file: 'contentScript.js'});
  });
}

在调用 sendMessage() 函数时,我希望看到一个带有页面 URL 的对象和一个充满链接的数组(对象形式的整个 html 元素,而不仅仅是 href)。但是我得到的输出是这样的:

{url: "https://www.freecodecamp.org/news/", links: Array(8)}
links: Array(8)
0:
__proto__: Object
1: {}
2: {}
3: {}
4: {}
5: {}
6: {}
7: {}
length: 8
__proto__: Array(0)
url: "https://www.freecodecamp.org/news/"
__proto__: Object

如您所见,URL 是从 contentScript 传递的,而数组是从 contentScript 传递到弹出窗口的,但不幸的是,该数组中充满了空项。

如何让链接数组显示实际内容,如下所示:

(8) [link, link, link, link, link, link, link, link]
0: link
...
baseURI: "https://www.freecodecamp.org/news/"
href: "https://cdn.freecodecamp.org/news-assets/prism-1-16-
outerHTML: "<link rel="stylesheet" type="text/css" href="https://cdn.freecodecamp.org/news-assets/prism-1-16-
__proto__: HTMLLinkElement
...
1: link
2: link
3: link
4: link
5: link
6: link
7: link
length: 8
__proto__: Array(0)

【问题讨论】:

  • 你不能发送 DOM 元素。仅支持简单类型,例如字符串/数字和此类类型的数组或对象。您可以简单地发送 URL 字符串。另请注意,弹出窗口仅在显示时运行,因此您可能需要切换消息传递的方向 - 弹出窗口将通过 chrome.tabs.sendMessage 向内容脚本发送消息,该脚本将在其 onMessage 中回复。

标签: javascript arrays google-chrome-extension message-passing


【解决方案1】:

是的,您不能将数组从弹出窗口传递给内容,反之亦然。解决它的方法是简单地为您的数组创建一个 foreach 语句并一次传递一个。

Popup.js:

 ary.forEach(element => {
      chrome.tabs.sendMessage(tabs[0].id, element);
 });

在您想要接收数组的脚本中,您只需重建它即可。

内容.js

 if(request != 'import' || request != 'scan'){
        arr.push(request);
 }

在上面的例子中,我只创建了两个“命令”。这两个命令是通过chrome.tabs.sendMessage(tab[0], &lt;arg&gt;);发送的

只要您指定如果要发送的参数没有任何意义而是要添加到数组中,您将成功地重建您的数组。我所说的例子在上面content.js

【讨论】:

    【解决方案2】:

    您不能发送 DOM 元素。仅支持简单类型,例如字符串/数字和此类类型的数组或对象。您可以简单地发送 URL 字符串。另请注意,弹出窗口仅在显示时运行,因此您可能需要切换消息传递的方向 - 弹出窗口将通过 chrome.tabs.sendMessage 向内容脚本发送消息,该脚本将在其 onMessage 中回复。

    礼貌 – wOxxOm

    【讨论】:

      猜你喜欢
      • 2020-10-12
      • 1970-01-01
      • 2016-07-09
      • 1970-01-01
      • 1970-01-01
      • 2017-06-11
      • 1970-01-01
      • 2014-03-12
      • 2014-07-16
      相关资源
      最近更新 更多