I have node js running a server that loads an html file with express. This html file has javascript that hides and shows a picture on the page with a button. I want to use the same function to hide and show the picture without the need for a button by calling the method in the main.js file that contains the rest of the application code. However, whenever I call the method it gives me a document not defined error. The button that calls the same function when clicked works however. I am not sure what the problem is (new to node).
web.js:
const hider = require("./public/script");
function site(){
const express = require('express');
const path = require('path');
const port = 3000;
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.listen(port, () => console.log("Server Started on: 127.0.0.1:"+port));
};
function hidePic(){
hider.hide();
}
module.exports = { site , hidePic}
File loaded by express. The button to hide the image works.
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="hide()">Try it</button>
<div id="picture1">
<img src="img.jpg" alt="img">
</div>
<script src="script.js"></script>
</body>
</html>
script.js:
function hide() {
var x = document.getElementById("picture1");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
module.exports = { hide }
Main program
main.js:
const web = require("./website")
web.site();
web.hidePic(); //Want this to hide picture in on webserver from within this file
Related
i am making a meme api webpage
i want the webpage to display a new meme fetched from reddit using reddit api.
i have completed the api and it perfectly shows new memes on every refresh.
i want to embed these images in readme markdown as images
for that i am using
<img src="https://mywebpage.com/">
but i am not getting images when embedded in md.
Here is the code of my webpage-
index.html-
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="script.js"></script>
</head>
<body>
<img src="loading.gif" id="meme" alt="meme didnt load :(" width="256px">
</body>
</html>
Script.js-
// function to fetch memes
function meme () {
let fetchRes = fetch("https://www.reddit.com/r/ProgrammerHumor/hot.json");
fetchRes.then(res => res.json()).then(d => {
// Generates a random number for the random meme
var randomNumber = Math.floor(Math.random() * 26)
// Actually gets the data from the api
var memeImg = d.data.children[randomNumber].data.url
var permalink = d.data.children[randomNumber].data.permalink
var postURL = `https://reddit.com${permalink}`
// setting the text to the data
document.getElementById('meme').src = memeImg;
})
}
// Reload page button
function reloadPage () {
document.location.reload(true)
}
// Calling the meme function
meme()
sorry for this very basic question.
So I want to know how to make buttons responsive.
I have a client.js and index.html as shown below
// Function to change the content of t2
function modifyText() {
const t2 = document.getElementById("t2");
if (t2.firstChild.nodeValue == "three") {
t2.firstChild.nodeValue = "two";
} else {
t2.firstChild.nodeValue = "three";
}
}
// Add event listener to table
const el = document.getElementById("myButton");
el.addEventListener("click", modifyText, false);
<table id="outside">
<tr><td id="t1">one</td></tr>
<tr><td id="t2">two</td></tr>
</table>
<button id="myButton">Click Me!</button>
When I run on codepen it works fine.
But when I try to run these locally, with a server.js like this
console.log('Server-side code running');
const express = require('express');
const app = express();
// serve files from the public directory
app.use(express.static('public'));
// start the express web server listening on 8080
app.listen(8080, () => {
console.log('listening on 8080');
});
// serve the homepage
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
and I change the html into having a script calling the client.js
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Example-1</title>
</head>
<body>
<button id="myButton">Click me!</button>
<table id="outside">
<tr><td id="t1">one</td></tr>
<tr><td id="t2">two</td></tr>
<script src="client.js"></script>
</table>
</body>
</html>
Then I run node server.js and I type localhost:8080 in my browser, the html file gets displayed but when I click the button, it doesn't cause any number changes.
How can I get these to work for real?
Also, ultimately I want the node.js server side to know a button has been pressed. Maybe print on the node.js console that "a button was pressed", whenever it was done on my browser. How can I achieve that?
What I want is to pass information from client side to server side easily but I am quite confused with how to do that and many people suggest different ways.
Edit:
Aligned file names.
I'd like to transmit a variable to another page with Node, in order to use it in the other page, I tried localstorage and defining a global variable, but no result for the moment, it says that node can't access the localstorage of the window :
test.js
var express = require('express')
var session = require('express-session')
var app = express()
app.post('/test1.html', function(req, res){
var user = "Jonhy DEEPPP";
console.log(user);
res.render( 'test1.html', { user:user } );
});
test1.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Titre</title>
</head>
<body>
<script>
alert(user);
</script>
</body>
</html>
I want to test the new Firefox Storage Access API to allow 1st party storage (cookie, local storage, indexeddb, ...) to an iframe of a different domain (but still under my control).
Parent Markup / code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Parent Domain</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.0/js.cookie.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jschannel/1.0.0-git-commit1-8c4f7eb/jschannel.min.js"></script>
</head>
<body>
<div>
Cookies: <ul class="cookie-data"></ul>
</div>
<iframe
id="rpc-gateway"
src="http://child.local:8080/iframe-firefox.html"
sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin"></iframe>
<script type="text/javascript">
var chan = Channel.build({
window: document.getElementById("rpc-gateway").contentWindow,
origin: "*",
scope: "testScope"
});
</script>
</body>
</html>
Child Iframe Markup / code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Child Domain</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.0/js.cookie.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jschannel/1.0.0-git-commit1-8c4f7eb/jschannel.min.js"></script>
</head>
<body>
<button onClick="onLoginClick()">Login</button>
<script type="text/javascript">
var chan = Channel.build({
window: window.parent,
origin: "*",
scope: "testScope"
});
let onLoginClick = function(trans, params) {
document.hasStorageAccess().then(hasAccess => {
if (!hasAccess) {
console.log("no access - requesting access");
return document.requestStorageAccess();
}
}).then(_ => {
document.hasStorageAccess().then(hasAccess => {
console.log("hasAccess:", hasAccess);
window.localStorage.setItem('foo', 'bar');
})
}).catch((err) => {
console.log("hasStorageAccess() failed", err);
});
};
</script>
</body>
</html>
When clicking on the "Login" button from the Child Iframe, the following log output is generated:
no access - requesting access # iframe-firefox.html:22:25
hasAccess: true # iframe-firefox.html:27:25
Request to access cookie or storage on “http://child.local:8080/iframe-firefox.html” was blocked because we are blocking all third-party storage access requests and content blocking is enabled. # iframe-firefox.html:28:24
The visible conclusion is:
The promise document.hasStorageAccess() resolves
The hasAccess parameter is initially 'false'
The promise of document.requestStorageAccess() is returned and resolves
The 2nd promise document.hasStorageAccess() resolves
The hasAccess parameter is now 'true'
nevertheless, simple storage access to local storage is not possible.
What do I do wrong?
More Info's:
Firefox Developer Edition Version 65.0b9
Content Blocking Setting:
This seems to be a bug in the version of Firefox you're using. I set up a test locally of what you have and in Firefox 69.0.1 (64 bit), I get no error and the value is stored to local storage. When I took the sandbox flag allow-storage-access-by-user-activation out of the parent iframe, the child failed to get permission for local storage, so that confirms that my setup was actually working properly. Here's what I did:
Created a Node.js/Express server for the parent:
const express = require('express');
const cors = require('cors');
const path = require('path');
const server = express();
server.use(cors());
server.use(express.static(path.resolve('./public')));
server.listen(8080, function() {
console.log('listening on *:8080');
});
Created a Node.js/Express server for the child (with different port to trigger same origin policy):
const express = require('express');
const cors = require('cors');
const path = require('path');
const server = express();
server.use(cors());
server.use(express.static(path.resolve('./public')));
server.listen(8081, function() {
console.log('listening on *:8081');
});
Created an index.html for the parent (pretty much the same as yours):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Parent Domain</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.0/js.cookie.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jschannel/1.0.0-git-commit1-8c4f7eb/jschannel.min.js"></script>
</head>
<body>
<div>
Cookies: <ul class="cookie-data"></ul>
</div>
<iframe
id="rpc-gateway"
src="http://127.0.0.1:8081/iframe-firefox.html"
sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin"></iframe>
<script type="text/javascript">
var chan = Channel.build({
window: document.getElementById("rpc-gateway").contentWindow,
origin: "*",
scope: "testScope"
});
// Added this to try out the JSChannel
chan.call({
method: "reverse",
params: "hello world!",
success: function(v) {
console.log(v);
}
});
</script>
</body>
</html>
And created iframe-firefox.html for the child:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Child Domain</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.0/js.cookie.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jschannel/1.0.0-git-commit1-8c4f7eb/jschannel.min.js"></script>
</head>
<body>
<button onClick="onLoginClick()">Login</button>
<script type="text/javascript">
var chan = Channel.build({
window: window.parent,
origin: "*",
scope: "testScope"
});
// Other end of the JSChannel call
chan.bind("reverse", function(trans, s) {
return s.split("").reverse().join("");
});
let onLoginClick = function(trans, params) {
document.hasStorageAccess().then(hasAccess => {
if (!hasAccess) {
console.log("no access - requesting access");
return document.requestStorageAccess();
}
}).then(_ => {
document.hasStorageAccess().then(hasAccess => {
console.log("hasAccess:", hasAccess);
window.localStorage.setItem('foo', 'bar');
})
}).catch((err) => {
console.log("hasStorageAccess() failed", err);
});
};
</script>
</body>
</html>
And everything worked as expected... So I'm feeling pretty sure that the issue is with the specific version of Firefox Developer Edition that you're using.
Also, here's a link to a zip of my setup if you want to give it a try on your end and see if this works differently than what you have: server.zip
Let me know if there's anything else I can do to help.
index.js file
const {BrowserWindow, app, globalShortcut} = require('electron');
const url = require('url');
const si = require('systeminformation');
let win = null
function boot() {
//console.log(process.type)
win = new BrowserWindow({
width: 600,
height: 500,
frame: false
})
var output = document.getElementById("output");
output.innerHTML = "hello world"
//win.loadURL(file:'//${__dirname}/index.html')
win.loadURL('file://' + __dirname + '/index.html');
win.on('closed', () => {
win = null
})
}
app.on('ready', boot);
**index.html file **
<!DOCTYPE html>
<html lang= "en">
<head>
<meta charset="UTF-8">
<title>Hello World</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="content">
<header>
<div class="option" id="close">X</div>
<div class="option" id="minimize">-</div>
</header>
<div id="text">z</div>
<h1>
<p id="output"></p>
</h1>
</div>
<script src="./assets/js/script.js"></script>
</body>
</html>
So I am using the value from the following snippet to be display into my HTML page
var output = document.getElementById("output");
output.innerHTML = "hello world"
Through this on my HTML page:
<h1>
<p id="output"></p>
</h1>
But it gives me the error:
"reference error :document is not defined "
By the way I am creating an Electron app. Just trying to display some data from my javascript page to html page.
As per the code you provided, you are referring to the document before it gets loaded.
var output = document.getElementById("output"); // <- here and
output.innerHTML = "hello world";
win.loadURL('file://' + __dirname + '/index.html'); // <- here
Check if the DOM is ready before manipulating it.
The name of your JavaScript file is index.js. But you are including script.js file in the script tag. Change the script tag to specify path of index.js file:
<script src="./path_of_file/index.js"></script>