How do I count the number of characters in a web page? - javascript

I am trying to create a web page that opens another web page when you click the "Try It" button, and then counts the number of characters in that webpage. Right now, this web page successfully opens the web page I ask it to open, but the length of the web page in characters is "undefined". I do not want to get rid of the XMLHttpRequest or the line of code below it, because I am planning to expand this webpage to enable it to parse the webpage by certain specific keywords later. Here is the code:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to open a new browser window.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
window.open("https://www.gutenberg.org/files/1065/1065-h/1065-h.htm");
var req = new XMLHttpRequest();
req.open('GET', 'https://www.gutenberg.org/files/1065/1065-h/1065-h.htm', false);
alert(req.length);
}
</script>
</body>
</html>
Any assistance that anyone can provide me would be greatly appreciated. Have a nice day.

First of all you need a flag header in the remote server that allow your url to make XMLHttpRequests.
Access-Control-Allow-Origin: * or Access-Control-Allow-Origin: yoururl.com
Another problem is that https version has a redirect to http version, then you could have problems if you are executing this from a https site, because of "mixed content" behaviour of client's browsers. Also synchronous XMLHttpRequest (false flag) is deprecated or going to be deprecated soon https://xhr.spec.whatwg.org/ .
If you perform this in the same domain (http gutenberg) it works. You should try executing this in your http server, and looking the console expecting not to have Access-Control-Allow-Origin restriction.
var req = new XMLHttpRequest();
req.open('GET', 'http://www.gutenberg.org/files/1065/1065-h/1065-h.htm', true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if(req.status == 200)
console.log(req.responseText);
else
console.log("Error loading page\n");
}
};
req.send(null)

Related

javascript opening a new window, setting its content AND its location without reloading that location for security

I am trying to implement an HTTP(due to memory resource limitation on embedded devices I can't use HTTPS) webserver security system.
I need to do this in case a hacker deploy a webserver with the same IP as mine (yes I know about IP conflict it shouldn't be possible but I tried and it worked) or hack my DNS server which will result in his server and mine to have the same domain for the browser and as result, the hacker can access the session storage in which I'm storing credentials (i know I shouldn't use session storage for credentials but due to many other vulnerabilities this is the best I can work with).
For this reason, before opening every page I must check that the received page is actually the original webpage and not a page sent by a hacker (phishing page for example) to extract the credentials, if it is a valid page I can continue and open it in the browser, and if not valid an alert is shown.
I check the validity of the page by checking a turning key only known by a (locally saved HTML file or a browser's extension) and the server with an ajax function. The key is sent with the page in the header:
var url="http://192.168.8.14";
......
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
if (xhr.getResponseHeader("identity_key") == identity_key)
{
//ORIGINAL WEB PAGE
}
}
};
xhr.open("GET", url+"?userIndex="+userIndex+"&identificationSalt="+identificationSalt, true);
xhr.send(null);
now i have all the validated html page inside the xhr.responseText which i would like to open inside a new tab or current tab and with the location pointing to url because the validated page contain relative paths and javascript src files with relatives paths which need the location to work like this :
<script src="sha.js"></script> or window.location.href = "http://"+window.location.host+"/controle
but when the location is pointing to the URL it mustn't reload the page otherwise the browser will load another page that is not validated.
I tried every way I can think of including this :
var url="http://192.168.8.14";
......
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
if (xhr.getResponseHeader("identity_key") == identity_key)
{
history.pushState(null, null, url);
document.documentElement.innerHTML=xhr.responseText;
}
}
};
xhr.open("GET", url+"?userIndex="+userIndex+"&identificationSalt="+identificationSalt, true);
xhr.send(null);
but it gave me this error:
Uncaught DOMException: Failed to execute 'pushState' on 'History': A history state object with URL 'http://192.168.8.14/' cannot be created in a document with origin 'null' and URL 'file:///C:/Users/ladne/Desktop/Untitled-1.html'.
at XMLHttpRequest.xhr.onreadystatechange (file:///C:/Users/ladne/Desktop/Untitled-1.html:73:33)
error
i also tried :
var page = window.open();
page.document.open();
page.document.location="http://192.168.8.14/";
page.document.write(xhr.responseText);
page.document.close();
can anyone help, please?

Not Able To Access Jenkins API From Plain JavaScript

I'm fairly new to API's and JavaScript so I'm not sure what wrong I'm doing here, please find the details below for the problem which I'm facing
Objective - Get Jenkins Details On A Webpage
As a part of my objective, I'm trying to make a web page from where I can trigger a Jenkins job and get the info of the build displayed on the webpage. As one of the part of the objective I want to trigger a Jenkins job from a button on my webpage.
Issue -
I created following script to do the operation -
<script>
function RunJenkinsJob() {
var xhr = new XMLHttpRequest();
xhr.open("POST", http://admin:114a2eae5e09d93b6ee831f248892ac581#localhost:8080/job/New_Test/build?token=Datacreation, true);
xhr.setRequestHeader('Content-Type', 'application/json');
}));
}
</script>
<head>
<style>body{background-color:#d0e4fe;}h1{color:orange;text-align:center;}p{font-family:"Times New Roman";font-size:20px;}</style>
</head>
<body>
<h1>Check Jenkins Job Build</h1>
<button type="button" onclick="RunJenkinsJob();"> Run Jenkins Job! </button>
</body>
</html>
However when I try to click this button nothing is happening, upon accessing this URL directly from browser I'm asked to provide username and password and then after refreshing new build gets triggered automatically.
Question
How to provide authentication for Jenkins in this JavaScript method so that on clicking the Button New Job can be triggered and also if I can get some pointers on how to extract the information about the build that also would be very useful.
System Details
OS - Windows
Jenkins Version - 2.235.1
-- Update 1 -
Please find the updated details below -
<!DOCTYPE html>
<html>
<script>
function RunJenkinsJob() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://admin:114a2eae5e09d93b6ee831f248892ac581#localhost:8080/job/New_Test/build?token=Datacreation", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send();
document.write(xhr.status);
}
</script>
<head>
<style>body{background-color:#d0e4fe;}h1{color:orange;text-align:center;}p{font-family:"Times New Roman";font-size:20px;}</style>
</head>
<body>
<h1>Check Jenkins Job Build</h1>
<button type="button" onclick="RunJenkinsJob();"> Run Jenkins Job! </button>
</body>
</html>
The following code worked for me.
Put this into your run jenkins job function. This would help debug if it cycles through all the 4 state changes and status it recieves.
var xhr = new XMLHttprequest();
var authorizationbasic = window.btoa("username:token");
xhr.onreadystatechange = function() {
if(this.readyState == 4)
{
console.log(this.status);
}
};
xhr.open("POST", "http://admin:114a2eae5e09d93b6ee831f248892ac581#localhost:8080/job/New_Test/build?token=Datacreation", true);
xhr.setRequestHeader('Authorization','Basic ' + authorizationbasic)
xhr.send();
If you still get status as 0 then you can check the CORS Filter setting in your jenkins installation.

Ajax & JavaScript | Limiting requests triggered by user

I am currently playing around with some Ajax code. I have come up with this scenario to try and mirror my problem to see if you, experts, can present a solution, thanks.
Scenario:
I have a HTML button like so: <p onclick="ajax_call();">Click</p>. Upon clicking this button it will launch an AJAX request to a php page like this:
function ajax_launch(){
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = ajax_launch_callback;
xmlhttp.open("POST", "/php_script", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
function ajax_launch_callback(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
// code to do something once response is here successfulyl
}
}
This then does some PHP code in the php_script file and returns an $output
Issue:
The php_script page that is called via AJAX is quiet heavy and makes several API and database calls making the page "slow" to load (which is perfectly fine). However at the moment, whilst the page is waiting for a response (it is still doing the php and not yet returned anything) a user can technically spam the button to launch many ajax calls. Ideally, this will just produce stress on the server and I need a way that once the request is pending and not come back, you cannot make further requests.
How can i achieve something like this?
Thanks in advance, looking forward for your solutions/consultation
ALSO:
By multiple requests, this is what i mean - see picture of when i spam click the button to launch several requests whilst the first one isn't done (not returned anything yet):
Image of chrome debugger (networks tab)
Although the mentioned javascript solutions here and in the linked question are a nice addition, you should really do this server-side as a spammer would not necessarily be using a browser and / or could have javascript disabled.
If you use sessions on the server, the session will be locked when a request is being processed so you will only process one request per user at a time. However, requests could queue up (that is perhaps what is showing in your networks tab data?) so you could complement that with a rate limit on for example the IP address.
You can try this:
var xmlhttp;
function ajax_launch() {
if (xmlhttp && xmlhttp.readyState == 4 || !xmlhttp) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = ajax_launch_callback;
xmlhttp.open("POST", "/php_script", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
}
function ajax_launch_callback() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// code to do something once response is here successfulyl
}
}
This things might be helpful:
Add this HTML
<div style="display: none;" id="screenblocker"> </div>
And this styles:
#screenblocker {
position:absolute;
left:0px;
top:0px;
right:0px;
bottom:0px;
background-color:#ffffff;
opacity:0.4;
filter:alpha(opacity=40);
z-index:9999999;
}
And script part:After the AJAX call
var e = document.getElementById('screenblocker');
if (e != null) {
e.style.display = 'block';
setTimeout("document.getElementById('screenblocker').style.display = 'none';", 5000);//considering 5 seconds to load, you can block longer if needed
}
And on AJAX success:
document.getElementById('screenblocker').style.display = 'none';

XMLHttpRequest not sent if web page location is changed afterwards

At some point my webpage is changing its location.href, resulting in the browser navigating to another page.
I would like to do a XHR POST request just before changing the page.
I would rather not wait for this XHR request completion, because not receiving 100% of the requests is OK but speed is paramount.
I tried this code, however the XHR request is NOT send by Firefox/Chrome, because of the location.href change right after.
<html>
<head></<head>
<body>
This is page test1.htm<br>
<input type="button" value="Go!" onclick="go();">
<script>
function go() {
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() { /* Do nothing */ };
xhr.open('POST', '/cgi-bin/hb.exe?action=remoteapppost', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send('action=remoteapppost&id=TEST');
// ==> this XHR request is NOT sent because of the following line:
location.href = "test2.htm";
}
</script>
</body>
</html>
If I do a breakpoint or move the location.href = "..."; inside the callback, everything is working fine (of course).
Any idea on how to send a XHR request just before leaving a webpage?
You want to use a combination of the beforeunload event and the new navigator.sendBeacon() API that's designed to not block navigation.

Origin null is not allowed by Access-Control-Allow-Origin.

I browse the answer for this question, but haven't find a good answer for me yet.
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if(request.readyState == 4 && request.status == 200){
var response = response.responseText;
window.open(response, "_blank", "location = 0, menubar = 0");
}
}
request.open("POST", "http://localhost/save.php", true)
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send("imag="+data);
the above is my javascript code. I did use http:// instead of file://, and I did put the files on XAMPP server. I also use header('Access-Control-Allow-Origin: *') in my save.php as someone mentioned, but I still get the same error.
Some help please...
I finally get it. When they say using http to open the file, they mean 2 things.
in javascript's open method, use http to open. I did this.
in the browser, also use http. I didn't do this.
before, I just double click the file and it opens in chrome
by File:// ...., I need to open the file in chrome manually
by typing in http:// ....
Silly mistakes...

Categories

Resources