Newby: index.js file doesn't work in index.html file - javascript

I'm new in Javascript world, currently I'm trying to implement a GUI using electron js framework.
Trying to reproduce the code from a tutorial, I got stuck on a code which seems not to work on my PC, basically even if I click on a button, the console is not logging anything (when it should have!!); the aim of the code is to refer to a button defined in an index.html file from a index.js containing the script and log a sentence when the button is clicked, but it seems like the script in the html file cannot access the .js file at all. Here I'm reporting the code from index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>my-app</title>
<link rel = "stylesheet" href="styles.css">
</head>
<body>
<button id = "button1" > START </button>
<script>
require('./index.js');
</script>
</body>
</html>
Here the code belonging to index.js file:
const electron = require("electron");
const button1 = document.getElementById("button1");
button1.addEventListener("click", startApp);
function startApp(){
console.log("Button clicked!");
};
Note:
I've tried to debug this code based on my very little knowledge of Javascript and electron:
I used document.getElementById("button1"); in index.html and it does work (the variable obtained was used to change button text color), but the same is not working when reported in the index.js file;
I tried console.log("In index.js"); in index.js but still it is not working!
From these results I thought the problem may be the .html and .js file communication; they are in the same folder. One more thing: I downloaded the tutorial code from GitHub and the problem is still present with the same actions at points 1 and 2.
Edit: I've omitted that I'm linking index.html window and displaying it in the main.js file, in fact the windows does show up, but the the click on the button doesn't produce any action.

Seemed to be a problem with the require module not working in .html file.
Solved by replacing it with <script src="index.js"></script>.

It appears that you shoud be using electron to load the index.html via BrowserWindowonce it is ready. app and BrowserWindow are from the electron module.
`const { app, BrowserWindow } = require('electron')`
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600
})
win.loadFile('index.html')
}
app.whenReady().then(() => {
createWindow()
})
From the quick start
In Electron, browser windows can only be created after the app module's ready event is fired. You can wait for this event by using the app.whenReady() API. Call createWindow() after whenReady() resolves its Promise.
For futher info see https://www.electronjs.org/docs/tutorial/quick-start
Hope this proves useful.

Related

Node.js and PowerShell Commands/Scripts

Here is the folder structure for my node.js project:
MySampleApp\
MySampleApp\Package.json
MySampleApp\Server.js
MySampleApp\public:
index.html - Invoked when server.js starts and shows "Click Me" button
fetchprocess.js - check button click and then show in DocumentElementID
user1.ps1 - runs Get-Process command to fetch processes
fetchprocess.js:
console.log('Client-side code running');
const button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
console.log('button was clicked');
document.getElementById('counter').innerHTML = "ClickedNow";
var ps = new shell({
executionPolicy: 'bypass',
noProfile: true
});
app.get("/", function (req, res) {
ps.addCommand("./user.ps1", [ {
name: 'guid', value: req.params.guid
} ])
ps.invoke().then(output => {
res.end(output); // This is to show the output in web browser
})
})
});
Index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<p id="counter">Loading button click data.</p>
<button id="myButton">Click me!</button>
</body>
<script src="fetchprocess.js"></script>
</html>
My objective is to execute "user1.ps1" when someone clicks on the "ClickMe" button and then show the data in HTML Div (Counter). When I try to run above code it throws an error that require is not defined in fetchprocess.js file.
Image:
I will have several scripts under the public folder that will be executed when someone clicks on other buttons on the web app. What is the best folder structure for such project.
Thank you very much
TL; DR; There is no way you can execute Node.js code in a browser.
Looks like you messaged up with libraries. You are trying to execute some Node.js code in the browser.
<script src="fetchprocess.js"></script>
Here you are loading the script in the browser. The truth is that Browser JS code does not have access to the platform things like PowerShell and it is not Node.js at all. If you need to execute Node.js code use Node.js executable.
UPD:
The workaround may be the following.
Spin up HTTP server locally with Node.js
Add an endpoint that runs the PS script once it receives a request.
On-click send AJAX request to your server.
But it worth noticing that it will work only on the machine where the Node.js server is running. Because it is not possible to run PowerShell from a browser.

Loading a html script from a typescript file

Im am currenlty working on a integration of a nps widget within a Chatbot. I cannot show you all the code, but i imported the html file inside the chat.ts file. I want to call the entire html file after a button press from the chatbot. I have tried a lot, but nothing seems to help.
this is the chat.ts code (small part of it)
private showAskNicely() {
// #ts-ignore
window.location.assign('npshtml.html');
}
private askNicelyButton() {
const el = document.getElementById('detractbut');
el.addEventListener('click', this.showAskNicely);
}
this is the npshtml file
<html>
<body id="try">
<p>
AskNicely Web Survey Popup Example for traditional websites.<br>
Running in 'force' mode.<br>
Responses will be recorded.
</p>
<script type="text/javascript" src="https://static.asknice.ly/dist/standalone/asknicely-in-app-conversation.js"></script>
<link href="https://static.asknice.ly/dist/standalone/asknicely-in-app-conversation.css" rel="stylesheet" type="text/css" charset="utf-8">
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
askNicelyConversation({
config: {
--- cannot show this part ---
},
customData: {
a_custom_property: 'business', // Optional - Send extra data about this customer for reporting and leaderboards
another_custom_property: 'New York' // Optional - Send extra data about this customer for reporting and leaderboards
}
});
});
</script>
</body>
</html>
I also have the button rendered inside another html file with css, but that all works fine.
I have it currently on windows.location.assign, so that it opens a new page. It would be ideal if the script could be triggered without opening a new page.
Using jquery.load does not work and does not give me a error of some sort.

Learning how to use ES6 import and modules getting Reference Error

I am just beginning to learn ES6 imports, with the hopes to transition an application to modular ES6. My current project has the following directory structure:
index.html
-scripts\
--function1.js
--function2.js
--globals.js
--main.js
My index.html file code is as follows:
<!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">
<title>Modular JS Example</title>
</head>
<body>
<button onclick="changevar1()">Change Var 1</button>
<button onclick="changevar2()">Change Var 2</button>
<script src="scripts/main.js" type="module"></script>
</body>
</html>
As you can see, I have two buttons which have onclick triggers assigned to them. These functions namely, changevar1() and changevar2() are found in files function1.js and function2.js respectively. And my entry point is main.js.
My main.js is as follows:
import {globalvar1 as globalvar1,
globalvar2 as globalvar2} from "./globals.js";
import {changevar1 as changevar1} from "./function1.js";
import {changevar2 as changevar2} from "./function2.js";
console.log(globalvar1, globalvar2,changevar1,changevar2);
My globals.js is where I declare some global variables which will be used by functions in either functions1.js or functions2.js and is as follows:
export let globalvar1 = "I am globalvar1";
export let globalvar2 = "I am globalvar2";
My function1.js has the function for the first button and is as follows:
import { globalvar1 } from "./globals.js" //do I need to import here?
export function changevar1() {
globalvar1 = "Now changed globalvar1"
console.log(globalvar1);
}
In the case above, I am importing the globalvar1 from globals.js and I am not sure if that is required, or if it will all come together in main.js?
My function2.js has the function for the second button and is as follows:
export function changevar2() {
globalvar2 = "Now changed globalvar2"
console.log(globalvar2);
}
In this case, I was not importing the globalvar2, just to see if it was not required.
Now the question is simply when you press the button how can you trigger either changevar1() or changevar2() to change the globalvar1 or globalvar2? I keep getting "Reference errors".
I have read several online documents and watched a few video tutorials online too to try to understand modular js.
Please excuse my lack of knowledge about modules and any help even if very basic knowledge is helpful.

How to get the Cloudinary upload widget to work?

All I am trying to do at this point is get the quick example working as shown here - https://cloudinary.com/documentation/upload_widget
This is my code -
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
</head>
<body>
<button id="upload_widget" class="cloudinary-button">Upload files</button>
<script src="https://widget.cloudinary.com/v2.0/global/all.js" type="text/javascript"></script>
<script type="text/javascript">
var myWidget = cloudinary.createUploadWidget({
cloudName: 'cloudname',
uploadPreset: 'uploadPreset'}, (error, result) => {
if (!error && result && result.event === "success") {
console.log('Done! Here is the image info: ', result.info);
}
}
)
document.getElementById("upload_widget").addEventListener("click", function(){
myWidget.open();
}, false);
</script>
</body>
</html>
When I click on the "Upload files" button the grey box of the upload widget does appear but all I see inside is a loading icon.
your code is working perfectly fine for me locally and on Codepen without making a single change to the code. I even uploading two pictures using it, which you should check if they appeared in your Cloudinary account. Don't worry, they are clean.
Since I can't check if the images were uploaded to your account, I created a Cloudinary account of my own and verified that the widget is indeed working fine. I only checked it by changing to my cloudName and preset.
Here's the Codepen Link
Your code below since Codepen Links need to have code accompany them.
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
</head>
<body>
<button id="upload_widget" class="cloudinary-button">Upload files</button>
<script src="https://widget.cloudinary.com/v2.0/global/all.js" type="text/javascript"></script>
<script type="text/javascript">
var myWidget = cloudinary.createUploadWidget({
cloudName: 'dw62s0tlm',
uploadPreset: 'rossm67'}, (error, result) => {
if (!error && result && result.event === "success") {
console.log('Done! Here is the image info: ', result.info);
}
}
)
document.getElementById("upload_widget").addEventListener("click", function(){
myWidget.open();
}, false);
</script>
</body>
</html>
This is from their support (which worked) -
The most common reason why that would happen is if the HTML file that contains the code for the widget is opened in the browser directly, via the file:// protocol. In order for this to work, the file should be opened from within your localhost through a web server via HTTP.
For example, if your system has Python installed you can quickly run a simple HTTP server in the same directory as your file which would make it accessible.
For example in Python 3:
python3 -m http.server
Python 2.7:
python -m SimpleHTTPServer
Then navigating to http://localhost:8000/index.html would run the code and should allow you to launch the widget.

Not load correctly resource in OPA5

I create my app using OpenUI5 and I want try to integrate OPA5 to test it.
I write my test page: TestOPA.html
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Opa sample for matchers</title>
<script id="sap-ui-bootstrap" src="https://openui5.netweaver.ondemand.com/resources/sap-ui-core.js"></script>
<link rel="stylesheet" href="https://openui5.netweaver.ondemand.com/resources/sap/ui/thirdparty/qunit.css" type="text/css" media="screen" />
<script>
(function () {
jQuery.sap.require("sap.ui.thirdparty.qunit");
jQuery.sap.require("sap.ui.test.Opa5");
jQuery.sap.require("sap.ui.test.opaQunit");
var Opa = sap.ui.test.Opa;
var Opa5 = sap.ui.test.Opa5;
module("Matchers");
opaTest("Should find a Button with a matching property", function(Given, When, Then) {
// Act
Given.iStartMyAppInAFrame("../index.html");
/* When.waitFor({
viewName : "view.Main",
controlType : "sap.m.Button",
matchers : new sap.ui.test.matchers.PropertyStrictEquals({name : "text", value : "Changed text"}),
success : function (aButtons) {
ok(true, "Found the button: " + aButtons[0]);
},
errorMessage : "Did not find the button with the property Text equal to Changed text"
});
Then.iTeardownMyAppFrame(); */
});
})();
</script>
</head>
<body>
<h1 id="qunit-header">Opa sample for matchers</h1>
<h2 id="qunit-banner"></h2>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
<div id="qunit-fixture"></div>
</body>
</html>
index.html is the root of my app. Inside the flow (not at start) I load resources that are not loaded properly.
I want load the resource http://localhost:8080/ZWebapp2/apps/appChangePwd/changePwd.js
but the console of browser show me a error to load the resource at http://localhost:8080/ZWebapp2/index.htmlapps/appChangePwd/changePwd.js
On all browsers it work fine (open http://localhost:8080/ZWebapp2/apps/appChangePwd/changePwd.js) but I have the problem when I start TestOPA.html
I have the same problem if I launch the my app (index.html) on internal Eclipse browser by Run as --> Web App Preview
Maybe you are referencing your files with a relative path, but you want an absolute one. Here is an example of how to do this with the jQuery.sap.require function of UI5:
JSBIN exmaple
The require statement in the bin should always create the correct request.
In your case it seems like you want declare an absolute path which means it will start building an URL after you host (localhost:8080). An relative path starts where your index.html is located.

Categories