无法在 IPCRenderer 中传递 Objects/Arrays,无法克隆对象 EventEmitter.i.send.i.send

Unable To Pass Objects/Arrays in IPCRenderer, An object could not be cloned EventEmitter.i.send.i.send

我无法将任何对象或数组传递给 IPCRenderer。

我在通过 ipcs 传递对象或数组时出错,我什至尝试使用 JSON.stringify 转换为字符串来发送,但它会将其转换为空对象字符串。

我试过传递一个文件列表,一个对象数组,甚至一个对象什么也没传递。只有字符串或手写对象有效。

我读到它使用结构化克隆算法并且此算法允许使用文件列表和数组

错误:

electron/js2c/renderer_init.js:74 Uncaught Error: An object could not be cloned.
    at EventEmitter.i.send.i.send (electron/js2c/renderer_init.js:74)
    at HTMLButtonElement.compressNow (ImageHandling.js:190)

我尝试了很多可能的解决方案,但没有任何效果

代码:


const compressNow = () => {
    ipcRenderer.send("image:compress", filess).  ///This is the error.
    // filess is a variable containing an array of selected files from an HTML input.
}

现在我尝试将 filess 作为 JSON.stringify 发送,我尝试将其作为对象发送,但没有任何效果,除非我手动编写一个虚拟对象或字符串。

这是我的 Github Repo for this project

有错误的文件J:-

ImageHandling.js

const fs = window.require('fs');
const {ipcRenderer} = require("electron")
const SELECT = (target) => document.querySelector(`${target}`)
var filess = []

const imgUploadInput = SELECT("#imgUploadInput")
const warning = SELECT("#warning")

const setImgBase64 = (imgEl, file) => {

    const ReadAbleFile = fs.readFileSync(file.path).toString('base64')
    let src = "data:image/png;base64," + ReadAbleFile

    imgEl.setAttribute("src", src)
    // El.src=src

    // console.log(`FIXED IMAGE # ${imgEl} `,ReadAbleFile)

}
const renderImages = () => {
    const files = filess && Array.from(filess)
    const defaultImg = SELECT("#defaultImg")
    const addImgBtn = SELECT("#addImgBtn")
    imgUploadInput.disabled = true;

    let numOfFiles = files.length

    if (numOfFiles < 1) {
        SELECT("#compressContainer").style.visibility = "hidden"
    } else {
        SELECT("#compressContainer").style.visibility = "visible"
    }
    if (numOfFiles > 49) {
        warning.innerHTML = `<b style="font-weight:bold; color:red;">WARNING:</b><br/> 
                               <span style="padding:10px;text-align:left">
                               Your processor/computer may not be able to process ${numOfFiles} Images at once, We recommend selecting less than 50 Images at once for better performance.
                                </span>
                                `;
    }
    addImgBtn.innerHTML = `LOADING.....`
    if (defaultImg && numOfFiles > 0) 
        defaultImg.remove();
    


    setTimeout(() => {

        if (files && numOfFiles > 0) {
            let displayImages = SELECT("#displayImages")
            displayImages.innerHTML = ""
            files ?. forEach((file, i) => {
                let divEl = document.createElement("div")
                let imgEl = document.createElement("img")
                imgEl.src = file.path

                imgEl.id = `PNG_${i}_${
                    btoa(file.name)
                }`
                divEl.className = "displayedImg"

                imgEl.setAttribute("onclick", `document.getElementById('ImageView').src=this.src`)


                const a = document.createElement("a")
                a.appendChild(imgEl)

                a.setAttribute("href", `#ViewImage`)
                a.className = "perfundo__link"


                divEl.appendChild(a)

                divEl.className = "displayedImg perfundo"

                displayImages.appendChild(divEl)


                if (i == files.length - 1) {
                    warning.innerHTML = "";
                    updateNumOfImages();
                }
                imgEl.onerror = () => setImgBase64(imgEl, file) // converting to base64 only on error, this make performance better and help us avoid freezes. (before this i was converting all images to base64 wither errored or not that was making computer freez)
            })
            addImgBtn.innerHTML = "+ Add MORE"
            imgUploadInput.disabled = false
            findDuplicate()
        }

    }, 0);
}

const hasDuplicate=()=>{
    let FileNames = [... filess.map(f => f.name)]
    let duplicateFiles = filess.filter((file, i) => FileNames.indexOf(file.name) !== i)

    return {FileNames,duplicateFiles,FilesLength:duplicateFiles.length}
}
const findDuplicate = (forceAlert = false) => {
    if (filess && filess.length) {
        let {FileNames} = hasDuplicate()
        let {duplicateFiles} = hasDuplicate()
        if (duplicateFiles.length) { // alert(``)

            let countFiles = duplicateFiles.length
            let fileStr = countFiles > 1 ? "files" : "file"
            console.log("result from removeDup=> ", filess, " \n dupfilename=> ", FileNames, " \n dupfiles=> ", duplicateFiles)

            let shouldNotAsk = localStorage.getItem("NeverAsk")
            let msg = `You've selected ${
                countFiles > 1 ? countFiles : "a"
            } duplicate ${fileStr}`
            let duplInner = `<span style='color:red'> 
                               <b>WARNING</b>
                               <p style="margin:0px;line-height:1">  ${msg} .  <button onClick="findDuplicate(true)" type="button"  class="btn btn-danger btn-rounded  btn-sm">REMOVE DUPLICATE</button></p>
                              </span>`
            if (! shouldNotAsk || forceAlert) {
                swal("DUPLICATE FILES DETECTED", `${msg} , Would you like to un-select duplicate ${fileStr} having same name?`, {
                    icon: 'warning',
                    dangerMode: true,
                    buttons: {
                        cancel: true,
                        ...forceAlert ? {} : {
                            never: "Never Ask"
                        },
                        confirm: "Yes !"
                    }
                }).then((Yes) => {
                    if (Yes == "never") {
                        localStorage.setItem("NeverAsk", true)
                        warning.innerHTML=duplInner

                    } else if (Yes) {
                        removeDuplicates()

                    }
                })
            } else {
                warning.innerHTML=duplInner
            }
        }

    }
}


const removeDuplicates = (showAlert=true) => {
    
    let {FileNames} = hasDuplicate()
    let {duplicateFiles} = hasDuplicate()
    let duplicateFileNames = duplicateFiles.map(f => f.name)
    let uniqueFiles = filess.filter((file) => ! duplicateFileNames.includes(file.name))
    filess = [
        ... uniqueFiles,
        ... duplicateFiles
    ]

    console.log("result from removeDup=> ", filess, " \n filename=> ", FileNames, " \n dupfiles=> ", duplicateFiles, "\n unique fil=> ", uniqueFiles)
    renderImages()
    if(showAlert){
    swal("DONE", "Removed Duplicate Files ", {icon: 'success'}).then(() =>{ 
        renderImages()
        setTimeout(() => {
             let hasDuplicateFiles = hasDuplicate().FilesLength
             if(hasDuplicate){//Re-check if any duplicate files left after the current removal process. 
                 removeDuplicates(false) //Re-run the function to remove remaining. false will make sure that this alert does not show and the loop does not continue.
             }
             renderImages()

        }, 10);
    
    })
   }
}




const updateNumOfImages = () => {
    warning.innerHTML = `
                <span style="text-align:left; color:green">
                        Selected ${
        filess.length
    } Image(s)
                 </span>
                 `;
}


const compressNow = () => {
    ipcRenderer.send("image:compress", filess)
    // alert("WOW")
}


CompressBtn.addEventListener("click", compressNow)

imgUploadInput.addEventListener("change", (e) => {
    let SelectedFiles = e.target.files

    if (SelectedFiles && SelectedFiles.length) {
        filess = [
            ... filess,
            ... SelectedFiles
        ]
        renderImages()
    }
})
// SELECT("#imgUploadInput").addEventListener("drop",(e)=>console.log("DROP=> ",e))

更新:-

我替换了这个:

const compressNow = () => {

        ipcRenderer.send("image:compress",filess)
    
}

进入这个:-

const compressNow = () => {

    filess.forEach(file => {
        ipcRenderer.send("image:compress",file.path )
    });
}

现在我通过 forEach 一个一个地发送文件,实际上它发送字符串“文件路径”所以它是如何工作的我仍然很困惑为什么我必须这样做?为什么我不能发送整个 fileList 我认为这种循环方法是一种不好的做法,因为它会消耗更多 CPU 它的一个额外循环但是如果我能够发送整个数组就没有必要了。

而不是发送图像,将它们保存在 fs 中并发送路径

从中删除 :compress。 .send 方法并尝试

参见 Behavior Changed: Sending non-JS objects over IPC now throws an exception。 DOM 对象等不可序列化。 Electron 9.0(及更新版本)在发送不可序列化的对象时抛出“无法克隆对象”错误。

在您的代码中,File and FileList 是 DOM 个对象。

如果您想避免使用 forEach,请尝试此代码:

const compressNow = () => {
    const paths = filess.map(f => f.path);
    ipcRenderer.send("image:compress", paths);
}