I am working with a third-party script, and I need to assign some functions to the window object, so that those functions are available to that third-party script (which will be running in the same browser window, called from the same domain). I must do this using ES6, using let
and modules (import
/ export
).
In ES5, I can do this:
//index.html
<script src="main.js"></script>
//third-party script will use window.myObj.blurt()
<script src="third-party-script.js"></script>
//main.js
var myObj = {};
myObj = {
blurt: function(){
console.log("Hello.");
}
}
blurt()
is now available to be invoked off of the window
object. I can put this in my browser console, and it will work: window.myObj.blurt()
.
I would like to do this, in ES6:
//index.html - note the type="module"
<script type="module" src="main.js"></script>
//third-party script will use window.myObj.blurt()
<script src="third-party-script.js"></script>
//main.js
import './my-window-functions.js';
//other existing code
//my-window-functions.js - NOT the third-party script - just my ES6 module system
let myObj = {};
myObj = {
blurt: function(){
console.log("Hello.");
}
}
Now window.myObj.blurt()
is undefined
. How do I assign functions to the window
object in this ecosystem?
window.open() - open a new window. window.close() - close the current window. window.moveTo() - move the current window. window.resizeTo() - resize the current window.
To conditionally import an ES6 module with JavaScript, we can use the import function. const myModule = await import(moduleName); in an async function to call import with the moduleName string to import the module named moduleName . And then we get the module returned by the promise returned by import with await .
1) require() In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.
Modules are the piece or chunk of a JavaScript code written in a file. JavaScript modules help us to modularize the code simply by partitioning the entire code into modules that can be imported from anywhere. Modules make it easy to maintain the code, debug the code, and reuse the piece of code.
In my-window-functions.js
you need to export the myObj
.
let myObj = {};
myObj = {
blurt: function(){
console.log("Hello.");
}
}
export {myObj};
Then in your main.js
you need to import the myObj
and assign it to the window object manually.
import { myObj } from'./my-window-functions.js';
window.myObj = myObj;
Then your 3rd party script can use the window.myObj.blurt()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With