Check if still connected to host with Javascript - javascript

In some place there is a policy which needs user to click button Continue to enter for example music streaming website.
Let's assume I want to use this website for a time longer than this policy accepts. After some period of time the music stops playing and after refreshing webpage - policy asks you for clicking Continue again, even if you have not left the page.
I'd like to make a script which would check if a connection still persists, but without website refreshing (because it plays music).
I've already created script which would click Continue, but don't know how to (and if it is possible) check connection, if connection is broken then refresh website and click Continue.
Can it be done with GreaseMonkey?
I enter http://deezer.com/
Script click Continue for me
I listen to music
Script is checking connection
if connection is ok go to 3.
Refresh website
Go to 2.
Click script:
if (document.title == 'Click continue')
{
var a = document.getElementById('continue-text');
a.children[1].click();
}
If no policy then the return of page is:
200 OK 318ms
If policy goes on, then it returns:
200 Forbidden 91ms

You can check the connection like this:
function checkConnection() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
// this might need some customisation:
var connected = document.getElementById("id_of_the_continue_button") ? true : false;
if (!connected) {
reconnect();
}
}
else {
reconnect();
}
}
}
// here you'll need a relevant url:
xmlhttp.open("GET", "http://deezer.com/", true);
xmlhttp.send();
}

Related

Opening multiple sites on the browser tabs with window.open

I have the following code and need to open two new tabs pointing to 2 web sites. For example: www.google.com and www.yahoo.com
It works only if I put one site in there
window.open("https://www.google.com");
but not when both lines
window.open("https://www.google.com");
window.open("https://www.yahoo.com");
Can you tell me what i need to do to be able to open both sites?
(function() {
document.getElementById("btnAsync").addEventListener('click', makeRequest);
function makeRequest() {
var httpRequest = new XMLHttpRequest(); // Initiatlization of XMLHttpRequest
if (!httpRequest) {
alert(' Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
};
window.open("https://www.google.com");
window.open("https://www.yahoo.com");
}
})();
<button id="btnAsync" type="button">Click Me</button>
I run your code. Both sites opened. But before it opens browser blocked popup window so i had to allow it to open. Try your code. And dont forget to allow popup after pressing button.
In the bad old days, it was common for malicious websites to fork bomb browsers by triggering an infinite loop of new windows.
They implemented protection against this by allowing new windows (and tabs) to be opened only when the function was triggered by a user event (e.g. a click but not a page load) and restricting this to opening a single window.
Some browsers may prompt the user to allow an additional window to open, but there is no way for a website to simply bypass this important security feature.

Check if page gets refresh or closed in Javascript

I want to detect whether page is refresh or closed.On close, I am clearing session. But my session getting clear on browser refresh also. I have searched but not found any solution.
I have used various method to solve:-
Method 1(this work but session out on refresh also.)
function HandleOnClose(event) /*called on onbeforeunload on body*/ {
if (event.clientY < 0) {
var request = GetRequest();
Urladd = "logout url goes here" //logiut URL work fine
request.open("POST", Urladd, false);
request.send();
}
}
function GetRequest() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
Method 2:
How to know whether refresh button or browser back button is clicked in firefox
Method 3:Identifying Between Refresh And Close Browser Actions

Text file comes back empty when loading with Ajax javascript

I've searched and searched and could not find a solution for this:
I'm trying to load .txt file contents with Ajax but the file comes back empty.
I checked the ready state and status. ready state is 4 which means that connection was set, data received , status is 0 which means error for loading http but I read on a forum that it is ok for a local file.
I really don't know what to do.
all help will be appreciated!
this is my code:
<script>
function load() {
var selectedValue = document.getElementById("mySelect").value;
var xhttp;
alert("in func")
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
try{
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
try{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
}
}
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && (xhttp.status == 200 || xhttp.status == 0)) {
document.getElementById("textDiv").innerHTML = xhttp.responseText;
alert(xhttp.responseText);
}
};
if(selectedValue == "Year 1"){
xhttp.open("GET", "file://year1.txt", true);
xhttp.send(null);
}
if(selectedValue == "Year 2"){
xhttp.open("GET", "year2.txt", true);
xhttp.send(null);
}
if(selectedValue == "Year 3"){
xhttp.open("GET", "year3.txt", true);
xhttp.send(null);
}
}
</script>
The issue is most likely the file protocol: file://year1.txt
try using a relative path instead, ie ./year1.txt
Edit..
I missed this the first time around.. you will get several hits to your callback function on a successful call. You'll get one where the status is zero first, then if successful you'll get another one with a 200. Why are you checking for both?
change this...
if (xhttp.readyState == 4 && (xhttp.status==200 || xhttp.status==0))
to this...
if (xhttp.readyState == 4 && xhttp.status==200)
OK! after EXTENSIVE research the problem was the infamous cross origin request problem (which does not allow access to local files as part of a security measure to insure you don't upload infected files &ct)
the solution is :
when initializing the variable for the XMLHttpRequest write:
xhttp = new XMLHttpRequest({mozSystem: true});
(notice the {mozSystem: true} inside the request)
AND IT SOLVES THE PROBLEM!!!
Thank you for your time, I hope this helps someone :)
My previous answer worked but not for long - after I restarted my computer the ajax stopped working at started throwing the cross origin error again. so- the best option I found that also works for all the browsers I checked (chrome, IE), is to set up a local server and run it from there.
here is a link for instructions:
https://www.maketecheasier.com/setup-local-web-server-all-platforms/
Good luck!

XMLHttpRequest state 2 waits for response from server

I'm trying to execute a block of code when my XMLHttpRequest reaches state 2. The reason why I want it to be in state 2 is that I don't want the user to wait for a response of the server( I would like to redirect the user at this point).
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 2) {
window.location.href = urlFromPreviousAjaxcall;
}
}
xmlhttp.open("POST", "url", true);
xmlhttp.send();
However the block of code inside the if(xmlhttp.readyState == 2) will only be called as soon as the server is done processing the call. This part has to be executed as soon as the call is made( without the waiting from the server).
In the documentation I found that state 2 is reached as soon as the call is send. However that is not the case.
Update:
the call I am trying to make involves calling a Api on the server( this takes time to complete). For the client it doesn't matter what happens to the call.The only thing I want is that the call is executed. So basicly I'm trying to gain speed here.
I know that as soon as I redirect the user, the code will stop running. However the call to the server should have been made(and send away).
What am I missing or doing wrong?
Thanks you all for your help.
I found the solution:
[HttpPost]
public void methode(String parameter,String parameter)
{
Task.Factory.StartNew<string>(() => RunTask(accessToken, parameter, parameter));
}
private string RunTask(String parameter, String parameter)
{
try
{
// Code to execute here
return "Done!";
}
catch (Exception e)
{
return "Error: " + e.Message;
}
}
At the server I started a Task. In this task I execute the long procces. It still takes a brief moment before the server returns the call to the user.
When debuggin ( in visual studio) you can see that the task is running without the presents of the user.
Note : all sessions are gone at the moment I redirected the user to an other page.

XMLHttpRequest status 0 on second load

I am experiencing an interesting issue when I am trying to load some data in .txt format from the same domain using XMLHttpRequest.
I am trying to load the data, parse it and then store it in localStorage
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var temp;
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
temp = xmlhttp.responseText;
}else{
alert("readyState: " + xmlhttp.readyState + "status: " + xmlhttp.status);
}
}
xmlhttp.open("GET","data/somedata.txt", false);
xmlhttp.send();
This code only works if I clean the history and cache; however, on second click of the same link, I would received "Readystate: 4, status 0" for some reason.
Does this has anything to do with localStorage?
if (!localStorage.somedata || localStorage.somedata.count(':') !== somedata.count(':')) {
localStorage.somedata = temp;
}
window.somedata = JSON.parse(localStorage.somedata);
There are two causes of status code of zero.
Making calls from the file protocol.
The page is refreshing/navigating away as the request is being made.
In your case I would assume it is #2. If you are using a button or a link to make the Ajax call, make sure to cancel the click action with either preventDefault or return false.
Sounds like a caching issue. Try either switching to a POST method, or appending a timestamp to the GET request querystring and see if that prevents the caching.
xmlhttp.open("POST", "data/somedata.txt", false);
or:
xmlhttp.open("GET", "data/somedata.txt?" + new Date().valueOf(), false);
Edit: If those don't work, modify your server configuration to send appropriate response headers for that file or type to not cache the response. Ie: Cache-Control: no-cache
Try xmlhttp.abort() before opening a new request.
It's a long shot but worth the try.

Categories

Resources