0

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();
        };
    }
Ortal Blumenfeld Lagziel
  • 2,415
  • 3
  • 23
  • 33
  • Your external file is a `ES module` so you should import it. The entire code will be import('http://......').then(m => { m.sayHi() }) – wOxxOm May 23 '21 at 14:07

2 Answers2

-2

export smth is syntax for javascript modules. If you want to address your function loaded in a plain javascript script you should make it accessible from global scope. As an example this should work as expected:

// example.js

alert('hello5');

self.sayHi = function sayHi(user) {
  alert(`Hello, ${user}!`);
}
aleksxor
  • 7,535
  • 1
  • 22
  • 27
-3

This post is will help you with all your confusions which are answered already. Please do look into this. Thank you

Hussain Ali
  • 45
  • 1
  • 6