I am trying to connect three file rule.js
, event.js
, action.js
using import and export in javaScript.
The functions in event.js
will get the data from the browser and when the and condition gets fulfilled then it will run the function from the rule.js
and after that action will be get executed.
// rule.js
import{actionOne} from 'action.js';
var scrollAndTime = (function(){
return function(){
console.log(actionOne());
}
})();
export{scrollAndTime};
// event.js
import { scrollAndTime } from 'rule';
var scrollPercentage = (function(){
var scrollRun = false; // This is for future use
if(!scrollRun){
return function(scroll){
console.log("I am Scroll.");
var height = document.documentElement,
body = document.body,
st = 'scrollTop',
sh = 'scrollHeight';
scrollRun = scroll;
var scrollPercent = (height[st]||body[st]) / ((height[sh]||body[sh]) - height.clientHeight) * 100;
return scrollPercent;
}
}
})();
var timeSpent = (function(){
var time = new Date();
var timeRun = false, // This is for future use
startTime = time.getTime();
if(!timeRun){
return function(){ // call this function by timeSpent()();
console.log("I am Time.");
return (new Date()).getTime() - startTime;
}
}
})();
// Handling and condition between scrollPercentage and timeSpent
var and=false;
addEventListener("click",function(){
if(!and){
var scrollAndTimeSpent=false;
if(scrollPercentage()>70 && timeSpent()>15000){
// this.alert("Executed!");
and=true;
scrollAndTimeSpent=true;
}
if(scrollAndTimeSpent){
// Tell rule engine that I have completed
// Execute this function.
scrollAndTime();
}
}
})
// action.js
var actionOne = (function(){
return function(){
// Do the following things and return the required thing.
return "ActionOne done!";
}
})();
export{actionOne};
// index.html - This is the page which is using these js files.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="main.css">
<title>Rule Engine</title>
</head>
<body>
<script type="module" src="event.mjs"></script>
</body>
</html>
Now in this when I am using type="module" I get (Access to Script at'file:///Users/praveenkumarrana/Desktop/Projects/ruleengine/event.mjs' from origin 'null' has been blocked by CORS policy: Invalid response. Origin 'null' is therefore not allowed access.) error.
And when I don't use it I get (Uncaught SyntaxError: Unexpected token { in Chrome.)
error.