How to make cloned DOM element JSON serializable

 ̄綄美尐妖づ 提交于 2019-12-13 05:31:32

问题


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

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