簡體   English   中英

如何將數組從內容腳本發送到彈出腳本

[英]How do I send an array from a content script to a popup script

我正在嘗試將頁面上所有鏈接的數組發送到我的 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 傳遞到 popup,但不幸的是,該數組充滿了空項目。

我怎樣才能讓鏈接數組顯示這樣的實際內容:

(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)

是的,您不能將數組從彈出窗口傳遞到內容,反之亦然。 解決方法是簡單地為數組創建一個 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], <arg>);

只要您指定,如果要發送的參數沒有任何意義但要添加到數組中,那么您將成功重建數組。 我正在談論的例子在content.js上面。

您不能發送 DOM 元素。 僅支持簡單類型,如字符串/數字和數組或此類類型的對象。 您可以簡單地發送 URL 字符串。 另請注意,彈出窗口僅在顯示時運行,因此您可能需要切換消息傳遞方向 - 彈出窗口將通過 chrome.tabs.sendMessage 向內容腳本發送一條消息,內容腳本將在其 onMessage 中回復。

由 – wOxxOm 提供

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM