josdejong / svelte-jsoneditor

A web-based tool to view, edit, format, repair, query, transform, and validate JSON
https://jsoneditoronline.org
Other
818 stars 108 forks source link

When operating the iframe parent-child page,tree mode view cannot automatically format expanded display #321

Closed itbencn closed 8 months ago

itbencn commented 8 months ago
<body>
    <div id='jsoneditor' style='width:100%;height:100%'></div>
</body>
<script type='module'>
    import { JSONEditor } from '/src/jsoneditor.js'
    const editor = new JSONEditor({
        target: document.getElementById('jsoneditor')
    })
    window.editor = editor;

    const setJson = function (json) {
        const content = {
            text: undefined,
            json: json
        }
        editor.set(content);
    }
    window.setJson = setJson;

    //Simulate the current page operation, everything is normal
    window.onload = function () {
        setJson({
            array: [1, 2, 3],
            boolean: true,
            color: '#82b92c',
            null: null,
            number: 123,
            object: { a: 'b', c: 'd' },
            time: 1575599819000,
            string: 'Hello World'
        });
    }
</script>
Snipaste_2023-10-13_18-16-20

When I directly call the setJson method on the current page to pass json parameters, the tree view can expand and display normally. But when I called setJson on the parent page by obtaining the window object, the text view was normal, and the tree view only displayed [object object] without automatic expansion or even manual expansion.

But if I call setJson on the parent page and pass the text parameter, the tree can expand and display normally

josdejong commented 8 months ago

Thanks for reporting. Can you create a minimal demo with an iframe showing how this goes wrong?

It looks like the content is stringified calling .toString() on a JavaScript object returns "[object Object]"

itbencn commented 8 months ago

Thanks for reporting. Can you create a minimal demo with an iframe showing how this goes wrong?

It looks like the content is stringified calling .toString() on a JavaScript object returns "[object Object]"

usage: access parent.html as local server running The vscode plugin I am using: Live Preview or Live Server

demo.zip

josdejong commented 8 months ago

Thanks for the demo code, I can indeed reproduce your issue. The cause here is that a JavaScript object created in the main thread is to be used in an iframe. That is a different JavaScript realm. The editor checks whether the input is an Object by checking value.constructor === Object, but that is false when the value is created in a different JavaScript realm. I'll make the function less strict to fix this issue.

As a workaround, you can do:

const setJson = function (json) {
    const jsonCreatedInIframe = JSON.parse(JSON.stringify(json))
    const content = {
        text: undefined,
        json: jsonCreatedInIframe 
    }
    editor.set(content);
}