module.export in inline html - javascript

when i try to export a variable in my HTML file and import in my main.js file it it throws an error:
SyntaxError: Unexpected token '<' that refeers to the <!DOCTYPE html> at the start of my index.html and i don't know why require doesn't grab the script with the module tag?
I just want the variable to show up in the main.js
I tried it with global.foo but that didn't work either
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Minecraft Launcher</title>
<link href="https://fonts.googleapis.com/css2?family=Open Sans" rel="stylesheet">
<style>
body {
background-color: rgb(0, 0, 0);
background-position: center;
color: white;
font-family: 'Open Sans', sans-serif;
}
</style>
</head>
<body>
<input type="button" value="Try me" id="startbutton">
<input type="text" name="input" id="input">
<script>
require('./renderer.js')
</script>
<script type="module">
module.exports.foo = 5;
</script>
</body>
</html>
main.js:
const { app, BrowserWindow } = require('electron')
// Variables
let startbutton;
app.on('ready', () => {
createWindow();
})
function startvariables() {
console.log("jup")
startbutton = window.document.getElementById("input")
console.log(startbutton.value)
}
function createWindow() {
var mainWindow = new BrowserWindow({
width: 950,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
mainWindow.loadFile('./index.html')
mainWindow.webContents.openDevTools()
}
setInterval(() => {
var foo1 = require('./index.html')
console.log(foo1)
}, 200)

That will definitely not work: node and electron's implementations of require expect a JS file, whether from the main or a renderer process. It is unable to extract the content of a <script> tag within an HTML file.
It looks like you may be trying to communicate some data from your renderer to your main process: electron offers IPC system for this very purpose.

Related

scope issue with iframe

I'm having a page with some inline css & javascript, the javascript on the original page contains some click and scroll logic which looks like this
$('#abc').on('click', function() {
$('html, body').scrollTop($('#xyz').offset().top)
});
it works fine on the original page;
Now I'm having a new page, which imports the original page as an iframe on the new page, but because it is iframe, the scope of the javascript code on original page inside this iframe is now bind to the iframe itself, and because it's bind to iframe itself, the $('html, body').scrollTop no longer works...
Is there anyway I can modify the original page to make it work through iframe?
for obvious security reasons, iframes are isolated in their own sandbox.
however, if you are in control of the code of the parent page and the iframe page, then you can use the message mechanism and pass your information through the event.data part.
here the example only passes text, for more extensive data, use JSON.stringify () / JSON.parse ()
file z1.html (parent)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Z1</title>
<style>
#iFrameZ2 { width: 400px; height: 150px; border: 1px solid red; }
#receiveTxt { margin: .5em; border: 1px solid blue; padding: .2em; width: 15em; }
</style>
</head>
<body>
<h4>main page (z1.html)</h4>
<input type="text" id="messageTxt" placeholder="a message...">
<button id="btSender">send to iframe</button>
<div id="receiveTxt">.</div>
<br> <br> iframe:<br>
<iframe id="iFrameZ2" src="z2.html" frameborder="0"></iframe>
<script>
window.onmessage = e =>
{
receiveTxt.textContent = e.data
/* ----------------------
if (e.data==='scroll')
{
document.querySelector('#xyz').scrollTop
}
------------------ */
}
btSender.onclick = _ =>
{
let info = messageTxt.value.trim()
if (info!='')
iFrameZ2.contentWindow.postMessage( info,'*')
}
</script>
</body>
</html>
file z2.html (iframe)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h6>z2.html</h6>
<input id="msgTxt" type="text" placeholder="send a message">
<button id="btSender">send msg</button>
<p id="getMsg">...</p>
<script>
btSender.onclick=_=>
{
let info = msgTxt.value.trim()
if (info!='')
window.parent.postMessage(info,'*')
}
window.onmessage = e =>
{
getMsg.textContent = e.data
}
</script>
</body>
</html>

Black border arround content in Electron

I use electron to convert a video game made with Phaser 2 to a .exe. But arround my content, I have some border or margin.
I tried to use full screen to change that, I also tried with useContentSize but the problem was not solve.
So this is my JS file :
const { app, BrowserWindow } = require('electron')
let win;
function createWindow () {
// Cree la fenetre du navigateur.
win = new BrowserWindow({
//width: 886,
//height: 473,
useContentSize : true,
autoHideMenuBar : true,
icon: "favicon.ico",
//met la fenetre sans bordure
//frame : false,
//fullscreen : true,
})
//load the index.html.
win.loadFile('src/junkbuster.html');
win.setMenuBarVisibility(false);
win.setMenu(null);
//win.setContentSize(1700,1200);
}
app.on('ready', function(){
createWindow();
console.log(win.getContentBounds());
//800,600 => 786, 563
console.log(win.getSize()+"=>"+win.getContentSize());
});
And this is my HTML file
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script src="./phaser.js"></script>
<script src="./index.js"></script>
<style type="text/css">
body {
background-color: black;
width:100vw;
height:100vh;
margin:0px;
}
body * {
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body>
</body>
</html>
According to Issue #9419, the workaround that worked for me was to avoid mainWindow.setResizable(false) and use this instead:
mainWindow.on('will-resize', (e) => {
//prevent resizing even if resizable property is true.
e.preventDefault();
});
This problem come from the scaleMangaer of Phaser 2. So to fix this you need to go to Boot init file and to change the your scaleMode.
Go to https://phaser.io/docs/2.6.2/Phaser.ScaleManager.html for more informations

TypeError : button is null but working fine in console

So I wanted to make a webpage in which on button click, the background color changes.
Its showing TypeError on loading in browser but its working fine after pasting same JavaScript on console.
Code snippet
var colors = ["#0af5fa", "#0ab1fa", "#0a3efa", "#560afa", "#b70afa", "#fa0ad9", "#fa0a65", "#fa0a1e", "#fa5e0a", "#facc0a", "#cbfa0a", "#69fa0a", "#0afa1b", "#0afa77", "#0afae5", "#0a8efa"];
var flag = 0,
blinkCount = 0;
function blink() {
if (blinkCount == 15) {
blinkCount = 0;
blink();
} else {
var h1 = document.querySelector("h1");
var body = document.querySelector("body");
h1.style.color = colors[blinkCount];
body.style.background = colors[blinkCount];
blinkCount++;
}
}
var button = document.querySelector("button");
button.addEventListener("click", blink);
button {
width: 50%;
height: 100px;
background: black;
margin-top: 300px;
margin-left: 300px;
}
h1 {
color: #0af5fa;
}
body {
background: #0af5fa;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<script src="../JavaScript/ex153.js"></script>
<link href="../css/ex153.css" rel="stylesheet">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div class="">
<button><h1>Click Me</h1></button>
</div>
</body>
</html>
In Browser [Error]
TypeError: button is null[Learn More] ex153.js:25:1
You're running the script before the document has been fully parsed - see how the <script> is above the <body> and its <button>?
Either give the script tag the defer attribute:
<script defer src="..
Or move it to the bottom of the body:
</div>
<script src="../JavaScript/ex153.js"></script>
</body>
</html>
Or wrap the whole script in a DOMContentLoaded listener:
document.addEventListener('DOMContentLoaded', function() {
var colors;
// other code
});

blocky - property of undefined

I am trying to create a custom block in blockly but can't seems to get it to work. I generated code from block factory and this is what I got:
//say_input.js
Blockly.Blocks['say_input'] = {
init: function() {
this.appendDummyInput()
.appendField("say")
.appendField(new Blockly.FieldTextInput("something"), "say_input");
this.setColour(230);
this.setTooltip("");
this.setHelpUrl("");
}
};
Blockly.JavaScript['say_input'] = function(block) {
var text_say_input = block.getFieldValue('say_input');
// TODO: Assemble JavaScript into code variable.
// var code = 'alert("Hello! I am an alert box and'+text_say_input+'!");';
var code = '...;\n';
return code;
};
then I import it into my html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Blockly Demo: Fixed Blockly</title>
<script src="js/blockly_compressed.js"></script>
<script src="js/blocks_compressed.js"></script>
<script src="js/msg/js/en.js"></script>
<script src="js/blocks/say_input.js"></script>
<style>
body {
background-color: #fff;
font-family: sans-serif;
}
h1 {
font-weight: normal;
font-size: 140%;
}
</style>
</head>
<body>
<button onclick="runCode()">Click me</button>
<div id="blocklyDiv" style="height: 480px; width: 600px;"></div>
<xml id="toolbox" style="display: none;">
<block type="say_input">
<field name="say_input">something</field>
</block>
</xml>
<script>
var demoWorkspace = Blockly.inject('blocklyDiv', {
media: 'js/media/',
toolbox: document.getElementById('toolbox')
});
function runCode(){
window.LoopTrap = 1000;
Blockly.JavaScript.INFINITE_LOOP_TRAP =
'if(--window.LoopTrap == 0) throw "Infinite loop."\n';
var code = Blockly.JavaScript.workspaceToCode(workspace);
Blockly.JavaScript.INFINITE_LOOP_TRAP = null;
try {
eval(code);
} catch (e) {
alert(e);
}
}
</script>
</body>
</html>
and load it to browser. immediately I got this error:
Cannot set property 'say_input' of undefined
The error is at the line:
Blockly.JavaScript['say_input'] = function(block) {
My custom block appear in the workplace so I am sure the linking is working.
I checked this video and seems like I am doing nothing wrong.
How can I resolve this?
I found the solution. I have to link javascript_compressed.js then everything just work.
<script src="js/javascript_compressed.js"></script>
make sure to link it before the custom block.js.

Javascript in Google Chrome popup extension not running

Hi I have run into a very weird problem.
I have a basic chrome extension which has a default popup.html document defined as follows:
<html>
<head>
<script type="text/javascript">
function disp() {
document.getElementById("test").innerHTML = "Bye";
}
</script>
</head>
<body>
<p id="test">Hello</p>
<button type="button" onclick="disp()">'Twas Nice to meet you</button>
</body>
</html>
Upon running the html file independently in a browser, it behaves as expected: clicking on the button changes the text of the p tag. However, from withing the chrome extension, in the popup the button does not seem to respond
Is this something to do with popups in general or something specific to my code?
Although you've found out you can circumvent the inline script "issue" (it is a security feature), below is what it would look like if you did not do that. This shows both how to call a notification and a "window"-based dialog.
manifest.json
{
"name": "Hello World!",
"version": "1.0",
"manifest_version": 2,
"description": "The first extension that I made.",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"notifications",
"create",
"tabs"
]
}
popup.html
<!doctype html>
<html>
<head>
<title>Getting Started with Extension's Popup</title>
<style>
body {
min-width:357px;
overflow-x:hidden;
}
img {
margin:5px;
border:2px solid black;
vertical-align:middle;
width:75px;
height:75px;
}
</style>
<!-- JavaScript and HTML must be in separate files for security. -->
<script src="popup.js"></script>
</head>
<body>
<div style="text-align: center;">
<button type="button" id="click">Show Notification</button>
<button type="button" id="dialog">Show Dialog</button>
</div>
</body>
</html>
dialog.html
<!doctype html>
<html>
<head>
<title>Dialog Prompt - Chrome</title>
<style>
body {
overflow: hidden;
margin: 0px;
padding: 0px;
background: white;
}
p {
text-align: center;
padding: 20px;
}
</style>
</head>
<body>
<p>This is a dialog prompt.</p>
</body>
</html>
popup.js
var notifier,
dialog;
function showNotify() {
var notify;
if (window.webkitNotifications.checkPermission() == 0) {
notify = window.webkitNotifications.createNotification(
"",
'Notification Test',
'This is a test of the Chrome Notification System. This is only a test.'
);
notify.show();
} else {
window.webkitNotifications.requestPermission();
}
}
function showDialog(){
chrome.windows.create({
url: 'dialog.html',
width: 200,
height: 120,
type: 'popup'
});
}
function init() {
clicker = document.querySelector('#click');
dialog = document.querySelector('#dialog');
clicker.addEventListener('click', showNotify, false);
dialog.addEventListener('click', showDialog, false);
}
document.addEventListener('DOMContentLoaded', init);
You can find the files to download here:
http://jfcoder.com/projects/chrometestdialogs/
manifest_version 2 doesn't allow user to enter the function inside the html file for security purpose, should we need to write all the function in separate file and import it to that html file like below
<head>
<script src="yourjsfile.js"></script> //All our functions are defined here
<script src="jquery.js"></script> // This is the jquery
</head>
and the function calling are not allowed here like onclick, onkeydown,onkeyup, etc...
<body>
<p id="test">Hello</p>
<button type="button" id="btn">Twas Nice to meet you</button>
</body>
In above "onclick="disp()" not allowed, and should assign a id
so should we need to create the event and definition must create from the .js file
So you should write a js file like below yourjsfile.js
document.addEventListener('DOMContentLoaded', function () {
$("#btn").on("click",function(){
disp();
});
});
function disp() {
document.getElementById("test").innerHTML = "Bye";
}

Categories