Search code examples
javascripthtml

document.write not working when pulling code from online


I'm making a game using emulatorjs and ruffle. It is supposed to be in a single file that can be downloaded and be run locally. I am trying to make another file that people can download that will auto-update. It works, but a lot of the scripts aren't working. Here is the code:

<script>
    fetch('https://trapjawws.github.io/funnyemulatorjs/index.html')
    .then(function (response) {
        switch (response.status) {
            // status "OK"
            case 200:
                return response.text();
            // status "Not Found"
            case 404:
                throw response;
        }
    })
    .then(function (template) {
        document.write(template);
    })
    .catch(function (response) {
        // "Not Found"
        alert(response.statusText);
    });
</script>

That code doesn't work. It's supposed to look like this: working one, the search bar loads, and the pokedex loads. It's main features are: having a search bar in the dropdown menu, loading games, and having a (working) Pokedex.

but instead it looks like this: search bar and Pokedex do not load, the search bar is not loading, and the Pokedex is not loading

On the one that doens't work, the built in Pokedex doesn't work, and the search bar doesn't work. These both pull assets from online, so yeah, that's probably important.

I have been playing around with it but it still hasn't been working. I found this site: https://toolki.com/en/html2js that does what I want perfectly, but I went through the site's code and I couldn't find the script that converts the code, because I want it to do it automatically when it pulls the code.

Basically, my goal is to have it pull the code from my Github site and write that code to the file, that can be downloaded and run locally.

Also, here is the code for the working one, if you guys wanted it: https://raw.githubusercontent.com/TrapjawwS/funnyemulatorjs/main/index.html

By the way, I'm new to HTML and js, so sorry if I'm making any stupid mistakes. :(


Solution

  • document.write(template);
    

    The question is... what exactly are you writing to with document.write? What is "document"?

    Just in case, here's how to properly use document.write()

    var W = window.open();  // create a new window
    
    W.document.open(); // create a write-stream to this window
    
    W.document.write('<div>sample html</div>'); // add some HTML
    
    W.document.close(); // close it off
    

    You’re not meant to overwrite your own document or you’re doing it wrong, and you’re not meant to write to a file on disk… well you can’t anyway!

    The idea is to create a new write stream and fill it with whatever it is you need regardless of the number of sources.