How to call functions from an external dynamically JavaScript file loaded from chrome extension js file?
I'm loading an external JavaScript file as follows:
var script = document.createElement("script");
script.type = "text/javascript";
script.src = 'http://127.0.0.1:8081/index2.js';
script.onload = function(){
alert("Script is ready!");
window.top.sayHi();
console.log('test');
};
document.body.appendChild(script);
The problem that I get an alert("Script is ready!"); but get window.top.sayHi(); is not a function, I also tried just to write sayHi(); but it's not working.
The external JavaScript file:
alert('hello5');
export function sayHi(user) {
alert(`Hello, ${user}!`);
}
Alert('hello5'); is called by the way I'm running my code from iframe
The following code also doesn't work:
if (script.readyState) { //IE
script.onreadystatechange = function() {
if (script.readyState === "loaded" || script.readyState === "complete") {
script.onreadystatechange = null;
console.log("[BANDEAU] script loaded");
alert('in1');
sayHi(); // window.top.testAlert() if needed
}
};
}
else {
script.onload = function() {
console.log("[BANDEAU] script loaded");
alert('in2');
sayHi();
};
}