How to pass nodelist object to background script?

自古美人都是妖i 提交于 2020-03-03 07:46:29

问题


I want to get all titles from reddit, and pass it to backgroundScript.js.

It shows all URLs in the console of the page but for some reason it shows me this message on background page:

My code:

manifest.json:

    {
  "manifest_version": 2,

  "name": "Testing stuff",

  "description": "This extension is for testing purposes",

  "version": "1.0",

  "background": {
    "scripts": [ "backgroundScript.js" ]
  },

  "content_scripts": [ {
      "exclude_matches": [ "*://*.reddit.com/r/*/ comments /*" ],
      "js": [ "contentScript.js" ],
      "matches": [ "*://*.reddit.com/r/*", "*://*.reddit.com/", "*://*.reddit.com/me/m/*", "*://*.reddit.com/user/*/ m /*" ],
      "run_at": "document_end"
    }  ],
    "permissions": [ "history", "tabs", "http://*/ *" ]

}

contentScript.js:

titleUrls = document.querySelectorAll("a.title");

for (i = 0; i < titleUrlsArray.length; i++) {
    var u = i + 1
    console.log(u + " " + titleUrls[i].href);
}

chrome.runtime.sendMessage(titleUrls)

backgroundScript.js:

chrome.runtime.onMessage.addListener(
    function (response, sender, sendResponse) {
        var data = response;

        alert("in backgroundScript.js, received " + data[1].href);
    }
);

Why does it show undefined on the background page when it shows all URLs just fine in the console of the main page? What am I doing wrong?


回答1:


You can't send DOM elements in a runtime.sendMessage() message

The message in runtime.sendMessage() must be "a JSON-ifiable object". DOM elements/nodes are not JSON-ifiable. Thus, you can not send them.

What you will need to do instead of trying to serialize the DOM element is, ultimately, determined by why you need this information in your background script.

You have stated that the information you need is the URLs from the .href property. You could build an array of those URLs and send that:

contentScript.js:

titleUrls = document.querySelectorAll("a.title");
var urlList=[];
for (i = 0; i < titleUrlsArray.length; i++) {
    var u = i + 1
    console.log(u + " " + titleUrls[i].href);
    urlList.push(titleUrls[i].href);
}

chrome.runtime.sendMessage(urlList);

backgroundScript.js:

chrome.runtime.onMessage.addListener(function(response, sender, sendResponse) {
    var urlList = response;
    alert("in backgroundScript.js, received " + urlList[0]);
});


来源:https://stackoverflow.com/questions/40881685/how-to-pass-nodelist-object-to-background-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!