KulaGGin KulaGGin - 7 days ago 6
Javascript Question

How to pass nodelist object to background script?

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:

http://i.imgur.com/ooYm0Je.png

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?

Answer

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]);
});