问题
I'm currently working with GitHub's Electron framework, and I'm trying to send a cloned DOM element from a preloaded script in a webview
through their IPC messaging system to my renderer process. Though, DOM elements are not able to be converted to JSON, and thus the received message is printing out an empty Object (Object {}
). Here's my code:
Preload.js
var ipc = require("electron").ipcRenderer;
function getData(element, trait){
if(trait === "id"){
var elem = document.getElementById(element);
}
else{
var elem = document.getElementsByClass(element);
}
var cloned = elem.cloneNode(true);
ipc.sendToHost("retrieve", cloned);
console.log("sent");
}
ipc.on("incoming", function(event, initData){
getData(initData.selected, initData.trait);
});
Renderer.js
loader.addEventListener("ipc-message", function (e) {
if (e.channel === "retrieve") {
console.log(e.args[0]); // I want this to print out the DOM object
}
});
loader.addEventListener("dom-ready", function() {
console.log("loaded");
var x = marks.list[i];
loader.send("incoming", x);
loader.openDevTools();
i++;
});
I can't just pick what I need out of the DOM, as I need everything inside the initData.selected
's element and it's attached CSS.
Is there a potential fix for this? And if not, then is there any way possible to send a DOM element between these two processes, possibly with another program or node.js module? Thanks.
回答1:
If the IPC only takes string arguments, then you should send the HTML instead, which means, use
ipc.sendToHost("retrieve", cloned.outerHTML);
and then this
var html = e.args[0],
dummy = document.createElement('div'),
cloned;
dummy.innerHTML = html;
// this will give you the node that you sent with all the inline CSS
cloned = dummy.childNodes[0];
console.log(cloned );
Note: We can only pass inline styling, the CSS loaded at the document level cannot be serialized with html
来源:https://stackoverflow.com/questions/35952712/how-to-make-cloned-dom-element-json-serializable