Search code examples
javascripthtmldomexternalinterfacedocument.write

Controlling the scope of a document.write call coming from a third party


I'm writing a webpage that relies on an external javascript file (that I have no control of), which returns data by using document.write's. Is there any way to dynamically call the function without it overwriting the whole document? Here's the most concise code I can think of:

<html>    
<head>
<script type="text/javascript">
    function horriblefunction () {
        document.write("new text");
    }
</script>
</head>

<body>
Starting Text...
<div id="pleasewriteinme"></div>
Other text...
<button onclick="horriblefunction();">Click</button>
</body>
</html>

The idea beginning that without altering "horriblefunction()" (as it's external) the new text could be placed in the div instead of overwriting the page. Is this possible or does the function have to be called inside the div as the page is created?

Thanks for you help


Solution

  • The only way to use document.write after the page has finished rendering is to temporarily replace the function with one of your own making that will shove the content into a div. E.g.

    function horriblefunction() { 
        var old_dw = document.write;
        document.write = function(text) { 
            document.getElementById( 'some_div' ).innerHTML = text;
        }
    
        // now call your external JS function that uses document.write
    
        document.write = old_dw;
    }
    

    This will work as long as the external JS is already loaded and you're just calling a function. If you need to load the JS (say, by inserting a new <script> tag into the DOM) remember that that operation is asynchronous, and you'll need to watch the DOM to know when it's safe to restore the old version of document.write.