0

I'm trying to load some html and javascript from one website without using iframe. I can render the html, css and it seems that the javascript files are being loaded, but I can't call functions from the loaded content.

I'm trying to load using fetch:

window.onload = function () {
    fetch(myURL)
        .then(function (response) {
            return response.text();
        })
        .then(function (body) {
            var dv = document.createElement('div');
            dv.innerHTML = body;
            document.body.appendChild(dv);
            //trying to call function here after appending the html content to my page
        });
}();

Is it possible, or it's blocked by browsers for security reasons?

Thiago Custodio
  • 17,332
  • 6
  • 45
  • 90
  • What happens if you try to call the function from setTimeout? (at the line you commented) like this: setTimeout(() => { callFunc() }, 0);. I suspect it doesn't work because of the rendering order. Calling setTimeout will make the call happen in the next tick of the event loop. – Karin C Sep 22 '21 at 21:23
  • it says 'VM63:1 Uncaught ReferenceError: init is not defined' – Thiago Custodio Sep 23 '21 at 13:25
  • Does this answer your question? [Executing – CBroe Sep 24 '21 at 10:42

1 Answers1

0

you have to explicitly add a script element.
so what works for sure is:

 let text = "<h1>Test</h1><script>const callMe = () => { alert('called'); }" + "&lt;/script>";
    const scriptStart = text.indexOf('<script>');
    const scriptEnd = text.indexOf('&lt;/script>');
    const script = text.substring(scriptStart + "<script>".length, scriptEnd);
    text = text.substring(0, scriptStart) + text.substring(scriptEnd + "&lt;/script>".length);
    element.innerHTML = text;
    const scriptElement = document.createElement("script");
    scriptElement.innerHTML = script;
    document.head.appendChild(scriptElement);
    callMe();