Chrome extension message being passed as object
I'm sending a message from the content script to the background page. The message is a URL which then gets ajax parsed in the background. When I console.log the data retrieved into background.js
the console log is pure html, but when I send the message back to my content script the message is suddenly in an object, and I'm not sure why.
Here is my code:
Content_Script.js:
chrome.runtime.sendMessage({greeting: URL}, function(response) {
console.log(response.farewell); //logs an object: Object {farewell: Object}
$('#stats-table2').append(response.farewell); //doesn't output anything.
});
Background.js:
chrome.runtime.onMessage.addListener(
function(message, sender, sendResponse) {
getStats(message, sender, sendResponse);
return true;
});
function getStats(message, sender, sendResponse){
$.ajax({
url: message.greeting,
dataType: 'text',
success: function(data) {
var info = $("<div>").html(data)[0].getElementsByTagName("table")[1];
if(info != undefined) {
console.log(info); //logs pure HTML into the console..
sendResponse({farewell:info}); //sends message back.
}
}
});
}
I have added comments for the important parts.. I can't seem to figure this out and it's driving me crazy. Any ideas? Thanks!
You can't pass DOM nodes with Messaging; data must be JSON-serializable, and DOM nodes are not.
Pass only data you really need (eg textContent
), then reconstruct the node on the other side.
上一篇: 从内容脚本发送消息到另一个
下一篇: Chrome扩展程序消息作为对象传递