JavaScript - Call function from another module inside HTML page - javascript

I have a module i18n.js which I import in my home.html, like this:
<html>
<head></head>
<body>
<script type="module" src="../js/lib/i18n.js"></script>
</body>
</html>
Inside the i18n.js module, I do the following:
export const t = () => {};
//
// Global scope
//
window.t = t;
I understand that accessing the global window object is the way to go in order to be able to call a method from other file inside an HTML page. But... why is this code not working?
<html>
<head></head>
<body>
<p><script>t("title")</script></p>
<script type="module" src="../js/lib/i18n.js"></script>
</body>
</html>
I get the error:
Uncaught ReferenceError: t is not defined

Because you're trying to execute t before it's available on the window, you get an error but running the function through the onload as #Rajesh suggested works properly.
const t = () => {
const pTitle = document.getElementById('pTitle');
if (pTitle){
pTitle.textContent = 'Hello World!';
}
};
//
// Global scope
//
window.t = t;
export {
t
};
<html>
<head></head>
<body onload="t()">
<p id="pTitle"> </p>
<script type="module" src="./src/js/i18n.js"></script>
</body>
</html>

Related

keeping scope while using import statment

I have three scripts: main.js, helper.js and module1.js. I need to include module1.js in helper.js, buf if I do this I'm getting an error message. It seems like the moment I use the tpye="module" tag on helper.js it's scope shifts. So how do I achieve the following without an error: (I don't want to make helper.js a module, which would solve the problem, because than I have to manualy import everything.)
index.html
<html>
<head>
<title></title>
</head>
<body>
<script type="module" src='helper.js'></script>
<script type="module" src='main.js'></script>
</body>
</html>
module1.js
export { f1 }
function f1() {
/* DIFFERENT STUFF */
return 0;
}
main.js
// import THINGS from STUFF;
(() => {/*STUFF*/})();
let res = importantValue;
helper.js
import { f1 } from "./module1.js";
const importantValue = f1();
Error Message:
main.js: Uncaught ReferenceError: importantValue is not defined

Having trouble with ES6 import / export variables

I am trying to compare text from two HTML pages using javascript using two separate external js files and importing the needed variable to be compared. However the function is not showing any result.
My first html is:
<!DOCTYPE html>
<html>
<body>
<span id='current-name'>John Hamish Smith</span>
<p id='new-billing'>0</p>
<script src='experiment.js' type="text/javascript"></script>
</body>
</html>
experiment.js below:
const currentName = document.getElementById('current-name').textContent;
const newBillingField = document.getElementById('new-billing');
const currBillingValue = Number(newBillingField.textContent);
let newBillingValue = currBillingValue + 1;
import {nameCheck} from './test2';
const testing = () => {
if(currentName === nameCheck) {
newBillingField.textContent = newBillingValue;
alert('hi there');
}
}
window.addEventListener('load', testing);
then my second html is simply:
<!DOCTYPE html>
<html>
<body>
<p id='userName'>John Hamish Smith</p>
<script src='./test2.js' type='text.javascript'></script>
</body>
</html>
and test2.js as follows:
let nameCheck = document.getElementById('userName').textContent;
export {nameCheck}
However, even with the names being the same, my newBillingValue is still 0.
(the alert is just to facilitate the function test)
thank you!

Problem with require() function in javascript

I am trying to implement the following code in which i try to read a json file in javascript. I have two files , let one be main.html which has the main javascript code let it be called main.js , and the other is imported.js
This is the main.html file
<!Doctype html>
<html>
<head>
Dwell time for workers
</head>
<script src = https://requirejs.org/docs/release/2.3.6/r.js></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script type="text/javascript" src="text.json"></script>
<script src="testing_file.js"></script>
<script type = "text/javascript"></script>
<script>
var Import = new import_file('osama'); // constructor
var out = Import.dwell_times()
console.log('out')
console.log(out[2]);
</script>
<body>
<h1> worker time : </h1>
</body>
</html>
This is the imported.js file
var that = null;
class import_file
{
constructor(title)
{
this.title = title;
that = this;
}
dwell_times()
{
console.log('osama')
var x = [5,4,3,2,1] ;
var y = x.toString();
console.log(y)
let parsed = require('./updated.json')
console.log(parsed) ;// Arham
return parsed;
}
}
var Import = new import_file('osama'); // constructor
var out = Import.dwell_times()
console.log('out')
console.log(out[2])
I am getting the following error
Uncaught Error: Module name "updated.json" has not been loaded yet for context: _. Use require([])
https://requirejs.org/docs/errors.html#notloaded
at makeError (r.js:417)
at Object.localRequire [as require] (r.js:1685)
at requirejs (r.js:2046)
at import_file.dwell_times (testing_file.js:16)
at imported.js:23
What do i do to solve this error ?
Require is unable to parse this out and automatically convert it. The solution is to convert to the callback syntax :
var moduleName = './updated.json';
require([moduleName], function(fooModule){
// do something
})

Javascript immediate function call from external function

I am trying to call the immediate function defined in test1.js on click of the button defined under html file. It always throws error "test is undefined". I am little bit aware that being a immediate function, it calls immediately, and so it returns the "undefined error". But is there any way I can call the immediate function (access methods, properties, etc.) on click of the button?
Thank you in advance.
//test1.js
var test = (function(){
alert(window);
var tmp = 'hello';
}());
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript" src="test1.js"></script>
<input type="button" id="btn1" value="ClickMe!" />
<script type="text/javascript">
var btn = document.getElementById("btn1");
btn.addEventListener("click",fun1,false);
function fun1(){
alert(test.tmp);
}
</script>
</body>
</html>
You have to modify your code so that the IIFE returns an object with a tmp property. Such as
var test = (function(){
alert(window);
var tmp = 'hello';
return {tmp:tmp};
}());
You need to explicitly return an object containing any data you want made available after you run the IIFE. (Just add the return as I did to the snippet below).
//test1.js
var test = (function(){
alert(window);
// you need to return any values you want accessible
return {
tmp: "hello"
}
}());
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript" src="test1.js"></script>
<input type="button" id="btn1" value="ClickMe!" />
<script type="text/javascript">
var btn = document.getElementById("btn1");
btn.addEventListener("click",fun1,false);
function fun1(){
alert(test.tmp);
}
</script>
</body>
</html>

Is it possible to call a function in main.js file from web to electron?

So I have a function in main file main.js which creates Electron BrowserWindow. Lets say:
function HelloWorld(name){
return 'Hello World! said ' + name;
}
Can I call it in the html page loaded by Electron?
<html>
<head>
<script type="text/javascript">
const hello = require('electron').HelloWorld
</script>
</head>
<body onLoad="alert(hello);">
</body>
</html>
Can I do that?
Yes you can.
In your main process (probably main.js) put this line in your main process :
global.HelloWorld = function(name){
return 'Hello World! said ' + name;
}
and in your HTML :
<html>
<head>
<script type="text/javascript">
let {remote} = require('electron');
const hello = remote.getGlobal("HelloWorld")(); // <-- () this is important
</script>
</head>
<body onLoad="alert(hello);">
</body>
</html>
But I suggest use ipcMain and ipcRenderer to send data between process.

Categories