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?
you have to explicitly add a script element.
so what works for sure is:
let text = "<h1>Test</h1><script>const callMe = () => { alert('called'); }" + "</script>";
const scriptStart = text.indexOf('<script>');
const scriptEnd = text.indexOf('</script>');
const script = text.substring(scriptStart + "<script>".length, scriptEnd);
text = text.substring(0, scriptStart) + text.substring(scriptEnd + "</script>".length);
element.innerHTML = text;
const scriptElement = document.createElement("script");
scriptElement.innerHTML = script;
document.head.appendChild(scriptElement);
callMe();