简体   繁体   中英

Preview Entire Document Typed in Textarea in New Window

I'm making a simple code editor for writing HTML/CSS/JS files online and offline. So far, everything is going great, but I'm trying to figure out how to accurately preview a full HTML document that is typed into the editor, doctype and all. So far for the editor, you can use "Open in New Tab" to open the document you type into a new window.

However, the only way I got it to work the way I want it to made me use a base64 encoded HTML file, which allowed me to output an ENTIRE document to a window, doctype and all.

If I used say, previewWinRef.document.write(editor.value) , that wouldn't work. After trying it, all it did was append to the current document.

How can I clear the contents of the preview window of its entirety and write the entire value of the editor textarea to the preview window WITHOUT using base64 encoding?

[EDIT]: Here is what is happening in the code:

editor.addEventListener('keydown',function(event){
            setTimeout(function(){
                if(previewWinRef){
                    previewWinRef.location = "data:text/html;base64,"+Base64.encode(editor.value);
                }
            },100);
        });

Basically I'm refreshing the result every time you push a key down, ONLY if you opened the preview window by going to File->Open In New Tab. For some reason, I can't seem to be able to access the document of the preview window, even though editor window created it and it's just a data URL? Window{} Screenshot

Here is the editor.

try this:

var win = window.open("about:blank", "title");
win.document.getElementsByTagName("html")[0].innerHTML = document.body.getElementsByTagName("textarea")[0].value;

Original answer updated.

You can use the documentElement property of the document object from the new tab. The catch here is that some browsers will complain about a same-origin-policy violation if the domain of the new tab's window.location is set to another site (or in your case a data string).

previewWinRef = window.open("about:blank");
previewWinRef.document.documentElement.innerHTML = editor.value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM