无法在 IPCRenderer 中传递对象/数组,无法克隆对象

Unable To Pass Objects/Arrays in IPCRenderer, An object could not be cloned EventEmitter.i.send.i.send(无法在 IPCRenderer 中传递对象/数组,无法克隆对象 EventEmitter.i.send.i.send)
本文介绍了无法在 IPCRenderer 中传递对象/数组,无法克隆对象 EventEmitter.i.send.i.send的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

I am getting error when passing an object or array through ipcs, I have even tried to send by converting to string using JSON.stringify but it converts it into empty object string.

我已经尝试传递一个文件列表,一个对象数组 &即使是一个物体也没有通过.只有字符串或手写对象有效.

I have tried passing a fileList, an array of object & even an object nothing passes. only string or handwritten objects are working.

我读过它使用结构化克隆算法和 fileList &该算法允许数组

I've read that it uses Structured Clone Algorithm and fileList & Array is allowed by this algorithm

错误:

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)

我尝试了许多可能的解决方案,但都没有奏效

I have tried many possible solutions but nothing worked

代码:


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.
}

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

Now i have tried to send filess as JSON.stringify, i tried to send it as an object but nothing works unless i manually write a dummy object or string.

这是我的 此项目的 Github 存储库

有错误的文件J:-

ImageHandling.js

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, " 
 dupfilename=> ", FileNames, " 
 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, " 
 filename=> ", FileNames, " 
 dupfiles=> ", duplicateFiles, "
 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 一个一个地发送文件,实际上是它的发送字符串文件路径".所以这就是它的工作原理我仍然很困惑为什么我必须这样做?为什么我不能发送整个文件列表我认为这种循环方法是一种不好的做法,因为它会消耗更多的 CPU 其一个额外的循环但是如果我能够发送整个数组就没有必要了.

Now here i am sending the files one by one via forEach, actually its sending string "file path" so thats how its working i am still confused why do i have to do this? why can't i send whole fileList i assume that this loop method is a bad practice because it will consume more CPU its one additional loop however it won't be necessary if i am able to send the whole array.

推荐答案

参见 行为改变:现在通过 IPC 发送非 JS 对象会引发异常.DOM 对象等是不​​可序列化的.Electron 9.0(和更新版本)抛出无法克隆对象".发送不可序列化对象时出错.

See Behavior Changed: Sending non-JS objects over IPC now throws an exception. DOM objects etc. are not serializable. Electron 9.0 (and newer) throws "object could not be cloned" error when unserializable objects are sent.

在您的代码中,FileFileList 是 DOM 对象.

In your code, File and FileList are DOM objects.

如果你想避免使用 forEach,试试这个代码:

If you want to avoid using forEach, try this code:

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

这篇关于无法在 IPCRenderer 中传递对象/数组,无法克隆对象 EventEmitter.i.send.i.send的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)