history.pushState error,i dont know why - javascript

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script>
window.onload = function(){
var oInput = document.getElementById('input1');
var oDiv = document.getElementById('div1');
var iNow = 1;
oInput.onclick = function(){
var number = randomNum(35,7);
oDiv.innerHTML = number;
history.pushState(number,'');
}
window.onpopstate = function(event){
var number = event.state || '';
oDiv.innerHTML = number;
}
function randomNum(alls,now){
var arr = [];
var newArr = [];
for(var i=1;i<=alls;i++){
arr.push(i);
}
for(var i=0;i<now;i++){
newArr.push(arr.splice(Math.floor(Math.random()*arr.length),1));
}
return newArr;
}
}
</script>
</head>
<body>
<input type="button" id="input1" value="35選7" />
<div id="div1"></div>
</body>
I don't know why history.pushState does not work, it throws the error:
history.html:14 Uncaught SecurityError: Failed to execute 'pushState' on
'History': A history state object with URL
'file:///C:/Users/TED/Documents/HBuilderProjects/javascript-%E7%9F%A5%E8%AD%98%E9%A1%9E/history.html' cannot be created in a document
with origin 'null' and URL
'file:///C:/Users/TED/Documents/HBuilderProjects/javascript-%E7%9F%A5%E8%AD%98%E9%A1%9E/history.html'.oInput.onclick # history.html:14

Don't pretend that file:/// is the same as "web pages": they didn't get loaded by the browser using the same mechanism that real web pages go through, and lots of things that web pages can do will not work for "plain files".
If you want to see how your code behaves as web page, using web APIs, then you'll need to load it properly using http(s). That means using a simple server (not even a full blow Apache or the like, just a one-liner http server like python -m SimpleHTTPServer, or php -S localhost:8000 or node.js's http-server or live-server packages, etc. etc.) and then load it through http://localhost:someport/yourfilename, where "someport" is whatever port number the one-line server says is being used, and "yourfilename" is obviously the name of your file.

Related

Uncaught Error: Module name "antlr4/index" has not been loaded yet for context on require.js

I try to use antlr4 on javascript, then read https://tomassetti.me/antlr-and-the-web/ and make but error has occurred.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="lib/require.js"></script>
<script type="text/javascript">
var antlr4 = require('antlr4/index');
var QueryLexer = require('gram/queryLexer');
var QueryParser = require('gram/queryParser');
document.getElementById("parse").addEventListener("click", function() {
var input = document.getElementById("code").value;
var chars = new antlr4.InputStream(input);
var lexer = new QueryLexer.queryLexer(chars);
var tokens = new antlr4.CommonTokenStream(lexer);
var parser = new QueryParser.queryParser(tokens);
parser.buildParseTrees = true;
var tree = parser.query();
console.log("Parsed: "+ tree);
});
</script>
</head>
<body>
<div id="inputs">
<textarea id="code">
* play with antlr4
* write a tutorial
</textarea>
<br/>
<button id="parse">Parse</button>
</div>
</body>
</html>
The error may cause on "var antlr4 = require('antlr4/index');".
I downloaded antlr4 from http://www.antlr.org/download/index.html and put same tier of "index.html". In lib directory there exist "require.js".
index.js
exports.atn = require('./atn/index');
exports.codepointat = require('./polyfills/codepointat');
exports.dfa = require('./dfa/index');
exports.fromcodepoint = require('./polyfills/fromcodepoint');
exports.tree = require('./tree/index');
exports.error = require('./error/index');
exports.Token = require('./Token').Token;
exports.CharStreams = require('./CharStreams').CharStreams;
exports.CommonToken = require('./Token').CommonToken;
exports.InputStream = require('./InputStream').InputStream;
exports.FileStream = require('./FileStream').FileStream;
exports.CommonTokenStream = require('./CommonTokenStream').CommonTokenStream;
exports.Lexer = require('./Lexer').Lexer;
exports.Parser = require('./Parser').Parser;
var pc = require('./PredictionContext');
exports.PredictionContextCache = pc.PredictionContextCache;
exports.ParserRuleContext = require('./ParserRuleContext').ParserRuleContext;
exports.Interval = require('./IntervalSet').Interval;
exports.Utils = require('./Utils');
I think there are no problems, because require path('antlr4/index') is not wrong.
But error has occurred. Please give me some idea.
The code you show in your question cannot work as-is with RequireJS. You'd have to write the require calls differently, or wrap all the require calls you have in a define so as to use the CommonJS support that RequireJS provides.
But the tutorial is not asking you to use RequireJS. if you go to the github repo that the writer of the tutorial provided, you'll see:
Require.js was obtained from https://github.com/letorbi/smoothie/blob/master/standalone/require.js
You have to use that file, which is not RequireJS, but something similar to it in the sense that it also loads scripts, and yet different from RequireJS in the sense that it seems to support the CommonJS module format as-is, which RequireJS doesn't.

Silence net::ERR_CONNECTION_REFUSED

Connecting to a non-existent web socket server results in loud errors being logged to the console, usually to the tune of ... net::ERR_CONNECTION_REFUSED.
Anyone have an idea for a hackaround to silence this output? XMLHttpRequest won't work since it yields the same verbose error output if the server is not reachable.
The goal here is to test if the server is available, if it is then connect to it, otherwise use a fallback, and to do this without spamming the console with error output.
Chrome itself is emitting these messages, and there is no way to block them. This is a function of how chrome was built; whenever a ResourceFetcher object attempts to fetch a resource, its response is passed back to its context, and if there's an error, the browser prints it to the console - see here.
Similar question can be found here.
If you'd like, you can use a chrome console filter as this question discusses to block these errors in your console, but there is no way to programmatically block the messages.
I don't know why do you want to prevent this error output. I guess you just want to get rid of them when debugging. So I provide a work around here may be just useful for debugging.
Live demo: http://blackmiaool.com/soa/43012334/boot.html
How to use it?
Open the demo page, click the "boot" button, it will open a new tab. Click the "test" button in the new tab and check the result below. If you want to get a positive result, change the url to wss://echo.websocket.org.
Why?
By using post message, we can make browser tabs communicate with each other. So we can move those error output to a tab that we don't concern.
P.S. You can refresh the target page freely without loosing the connection between it and boot page.
P.P.S You can also use storage event to achieve this.
boot.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>boot page</title>
</head>
<body>
<button onclick="boot()">boot</button>
<p>BTW, you can boot the page without the button if you are willing to allow the "pop-up"</p>
<script>
var targetWindow;
function init() {
targetWindow
}
function boot() {
targetWindow = window.open("target.html");
}
boot();
window.addEventListener('message', function(e) {
var msg = e.data;
var {
action,
url,
origin,
} = msg;
if (action === "testUrl") {
let ws = new WebSocket(url);
ws.addEventListener("error", function() {
targetWindow.postMessage({
action: "urlResult",
url,
data: false,
}, origin);
ws.close();
});
ws.addEventListener("open", function() {
targetWindow.postMessage({
action: "urlResult",
url,
data: true,
}, origin);
ws.close();
});
}
});
</script>
</body>
</html>
target.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>target page</title>
</head>
<body>
<h4>input the url you want to test:</h4>
<textarea type="text" id="input" style="width:300px;height:100px;">
</textarea>
<br>
<div>try <span style="color:red">wss://echo.websocket.org</span> for success result(may be slow)</div>
<button onclick="test()">test</button>
<div id="output"></div>
<script>
var origin = location.origin;
var testUrl = origin.replace(/^https?/, "ws") + "/abcdef"; //not available of course
document.querySelector("#input").value = testUrl;
function output(val) {
document.querySelector("#output").textContent = val;
}
function test() {
if (window.opener) {
window.opener.postMessage({
action: "testUrl",
url: document.querySelector("#input").value,
origin,
}, origin);
} else {
alert("opener is not available");
}
}
window.addEventListener('message', function(e) {
var msg = e.data;
if (msg.action === "urlResult") {
output(`test ${msg.url} result: ${msg.data}`);
}
});
</script>
</body>
</html>

Unable to make tracking pixel send data to api

I'm trying to use this library to implement a tracking pixel.
I'm testing in my localhost machine with Apache.
I have a index.html page at htdocs/openpixel/index.html
with the following content:
<html>
<head>
Test Pixel
</head>
<body>
Test Pixel
<!-- Start Open Pixel Snippet -->
<script>
!function(e,t,n,p,o,i,a,s,c){e[o]||(a=e[o]=function(){a.process?a.process.apply(a,arguments):a.queue.push(arguments)},a.queue=[],a.t=1*new Date,s=t.createElement(n),s.async=1,s.src=p+"?t="+Math.ceil(new Date/i)*i,c=t.getElementsByTagName(n)[0],c.parentNode.insertBefore(s,c))}(window,document,"script","http://127.0.0.1/openpixel/v1/openpixel.js","opix",864e5),opix("init","ID-123"),opix("event","pageload");
</script>
<!-- End Open Pixel Snippet -->
</body>
</html>
This is openpixel.js, where it should send the data to an endpoint
...
window.onload = function () {
var aTags = document.getElementsByTagName('a');
for (var i = 0, l = aTags.length; i < l; i++) {
aTags[i].onclick = function (e) {
if (Url.externalHost(this)) {
Config.externalHost = { link: this.href, time: now() };
}
}.bind(aTags[i]);
}
};
}(window, document, window["opix"], "opix", "http://localhost:3000/pixel_data", 1));
...
I also created an endpoint api in Node.JS to receive this pixel. When I test it with a browser get resquest it is responding.
app.get('/pixel_data', function(req, res) {
console.log(req.query);
});
The problem is when I access pixel.html, the endpoint /pixel_data is logging nothing. I'm trying to understand the problem here.
You're Node.js server is not able to see the query string because it looks like your server is on localhost:3000 and you are sending a request to 127.0.0.1/openpixel/v1/openpixel.js.
Change your pixel tag to request localhost:3000 by changing http://127.0.0.1/openpixel/v1/openpixel.js to http://localhost:3000/pixel_data.

Save Button-Click Count in localStorage in javascript

I made a button click counter for a website using some JavaScript.
The counter works well, but now I'm stuck in making the saving of the count. You know, if I click the button 3 times, the text says 3 Times. But I want to save that value so if the user refreshes the page, it should display 3 Times again.
I knew of using localStorage, I followed a simple tutorial and applied it to my code, but it does not seem to be working. When I run the page in Microsoft Edge and see the Debug page (F12), the console throws an error that says: Unable to get property 'getItem' of undefined or null reference. I searched in other posts but no one of these could solve my problem. It seems to be stuck when retrieving the value in localStorage.
This is my code:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Increment count when button is clicked</title>
</head>
<body>
<input type="button" value="Registrar" id="countButton" />
<input id="ocityField" type="text" value="" placeholder="Ciudad de Origen"/>
<input id="cityField" type="text" value="" placeholder="Ciudad de participación"/>
<input id="name" type="text" value="" placeholder="Nombre"/>
<p>Personas Registradas: <span id="displayCount">0</span></p>
<script type="text/javascript">
var count = 0;
var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");
var textbox = document.getElementById("ocityField");
var textboxa = document.getElementById("cityField");
var textboxb = document.getElementById("name");
if(window.localStorage.getItem('count')){
var savedcount = window.localStorage.getItem('count');
count = window.localStorage.getItem('count');
}else{
count = 0;
}
display.innerHTML = count;
button.onclick = function(){
var mystring = textbox.value;
var mystring2 = textboxa.value;
var mystring3 = textboxb.value;
if(!mystring.match(/\S/) || !mystring2.match(/\S/) || !mystring3.match(/\S/)) {
alert ('Empty value is not allowed');
return false;
} else {
count++;
window.localStorage.setItem('count', count);
display.innerHTML = count;
textbox.value = "";
textboxa.value = "";
textboxb.value = "";
return true;
}
}
</script>
</body>
</html>
I tried using window.localStorage and just localStorage but no one did work.
May be that you use the IE browser does not support localStorage,The code can run in Chrome49.
Can I Use localStorage, here you can check what browser supports localStorage with version numbers.
Alternate way to store data on client side is cookies if localStorage doesn't supported by browser.
You can also use third party plugins like Modernizer, to check whether browser supports or not.
Modernizr.localstorage if it evaluate to true the browser supports localStorage.
Following example demonstrates localStorage and cookies depending on browser compatibility. uses Modernizer and jQuery
codepen

Posting form values securely from one page to another on client-side using pure Javascript and NO server-side technology

I need to POST form values from one page to another using Javascript.
Now, I know that I could use a server-side technology like ASP.Net or PHP to post values but I am not allowed to use any server side script.
I am aware that using the GET method, I can pass the form values as a query string but the values will not be passed securely (which is an important requirement!)
The conditions listed below:
This code should take the values that are posted to the page and
repost to target page. HTTP POST only (not get).
In no cases, even error, the request should not stop on this bridge page.
The script needs to handle multiple posted values.
Try to use standard javascript (no 3rd party library)
Script needs to work in IE, FF, Safari, most standard browsers
Can anyone please help me find a solution to this or point me to some resource that will help me find the soln? Thanks in advance. Below is the code for passing values as a query string. Can I modify this so that my above requirements are satisfied?
FORM
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function goto_page(page) {
var usbnum = document.getElementById('usbnum').value;
var usbcode = document.getElementById('usbcode').value;
var q_str = '?usbnum=' + usbnum + '&usbcode=' + usbcode;
var url = page + q_str;
window.location = url;
}
</script>
</head>
<form id="form1" method="post">
<div>
USB No: <input name="usbnum" id="usbnum" type="text" size="80" /><br />
USB Code: <input name="usbcode" id="usbcode" type="text" size="80"/>
</div>
Next
</form>
</body>
</html>
BRIDGE PAGE
<html>
<head>
<title>Bridge Page</title>
<script type="text/javascript">
function get_params() {
var url = window.location.href;
var q_str_part = url.match(/\?(.+)$/)[1];
var val_pairs = q_str_part.split('&');
var params = {};
for (var i = 0; i < val_pairs.length; i++) {
var tmp = val_pairs[i].split('=');
params[tmp[0]] = typeof tmp[1] != 'undefined' ? tmp[1] : '';
}
return params;
}
function write_params() {
var params = get_params();
var txt = 'Hello ';
for (var i in params) {
txt += params[i] + ' ';
}
var body = document.getElementsByTagName('body')[0];
body.innerHTML += txt;
}
function write_params() {
var params = get_params();
var num_container = document.getElementById('usbnum');
var code_container = document.getElementById('usbcode');
num_container.innerHTML = params.usbnum;
code_container.innerHTML = params.usbcode;
}
</script>
</head>
<body onLoad="write_params()">
</body>
</html>
POST data can only be handled by server side code. There is no way you can use them in your javascript without help from a server side code.
You can only use GET or you can think about cookies. But at other hand, why do you want to change current page?! you can use AJAX to load more data without refreshing and no need of posting or getting variables.

Categories