How to execute some jQuery or JavaScript code after a redirect has completed - javascript

How can I execute jQuery/JS code as soon as a jQuery/JS redirect like...
$(location).attr('href','/target_path');
...or...
window.location.href = "/target_path";
...has finished loading the new page?
Specifically, I need to pass an alert message and insert it into and display it (enclosed in some HTML) on the new page.

You can't. Once the redirect happens you are no longer on that page. You can't execute code on a page you are no longer on. If you want the next page to do something then you need to pass, either by cookie or URL parameter, a flag that instructs it to do so.

It is impossible to tell JavaScript to execute some code after a redirect.
However you have different options:
Pass a string in the redirect URL and then do something on "ready"
Store some information in a cookie and then do something on "ready"
Store some data using DOM storage (namely sessionStorage) if you don't mind the smaller browser support

You can't do that in the page that's redirecting. You can read the referrer in the landing page (document.referrer), and then decide whether to display an alert based on that, though.

var x = "It's some text";
var loc = '/target_path';
loc += '?message=' + encodeURI(x);
The JS file on the new page can then look at the query string to see if a message is there, and do the required action if it's detected.
You can use window.location.search on the new page to see what's there, although I'd recommend hunting for a deparam function in a library to turn the query string into a more usable object.

Related

JavaScript Redirect to Page Another website based on URL

Using JavaScript, how can I make it redirect to another site based on the URL?
(Example)
If someone goes to https://example.com/12345, it will redirect them to https://example.net/12345.
And if someone goes to https://example.com/abc123456, it will redirect them to https://example.net/abc123456
How can I do this?
In the place that you have hosted that domain, See if you can find something that makes it a single page app or a way to rewrite all urls to one page so that it doesn't show 404 not found. (not certain how you can do that, I only done it with firebase hosting, it has a way of configuring it so that no matter what url you give it, it always shows you the same page, and also the url doesn't get changed ) if you can do that, this is the code you need:
let pathname = location.pathname //if the url is https://example.net/1234, the path name will be /1234
location.href = "https://example.net" + pathname //if you add that to this string, it would be https://example.net/1234
You can use following code for that:
location.href = 'https://example.net/12345';
location.href = 'https://example.net/abc123456';
Or used following code for that:
location.replace('https://example.net/12345');
location.replace('https://example.net/abc123456');

On page load redirect to the same page with querystring

Hi so i am getting a cookie passed in from another website which brings in some data i need to put in the query string.. i know how to put it in the query string that's not my questions.
My question is what jquery function can i use onpage load which will redirect to the query string.. now i don't want to page to load twice i want this to happen and look like it has only loaded once. I have tried to use a .one jquery but that's not needed anymore as the if statement will validate if the query string needs to change. Also that function is not working correctly anyway.
$(document).one('load', function() {
if (window.location.pathname == '/items.aspx'){
window.location.replace("items.aspx?item1=a80af972-4f78-de11");
}
});
any ideas would be great.
Thanks
You could use window.location.href="items.aspx?item1=a80af972-4f78-de11"but that will also reload the page. Depending on your users internet connection it could seem like one page load.
Another thing worth noting: You are waiting for $(document).on("load") which gets fired when the page is loaded which is exactly what you don't want.
Try this for speed increase:
$(document).ready(function() {
if (window.location.pathname == '/items.aspx'){
window.location.href = "items.aspx?item1=a80af972-4f78-de11";
}
});
Still - this is a thing to do on the server side. Something in the backend like "if item1 is undefined load item a80af972-4f78-de11" would be best.

Is it possible to delete an entire Webpage when the user navigates away?

If the user navigates off the webpage, is it possible to execute a php script?
I know that Javascript can be executed..
$(window).bind('beforeunload', function(){
return 'DataTest';
});
Cookies might work, but I am not sure how a listener could track an expired cookie, and then delete the correct webpage.
A sample file system is like this:
user0814HIFA9032RHBFAP3RU.php
user9IB83BFI19Y298RYBFWOF.php
index.php
listener.py
data.txt
Typically, to create the website, php writes to the data.txt and the Python listener picks up this change, and creates the file (user[numbers]). As you might think, these files stack up overtime and they need to be deleted.
The http protocol is stateless, therefore users simply can not "navigate away".
The browser requires a page, the server returns it, and the communication stops.
The server doesn't have reliable methods to know what the client will do with that page.
Disclaimer: I'm not sure, as Fox pointed out, that this is the right way to go in your case. I actuallly upvoted Fox's answer.
However, if you absolutely need to delete each page right after the user left it, use this:
$(window).bind('beforeunload', function() {
$.ajax('yourscript.php?currentUser=0814HIFA9032RHBFAP3RU');
});
Then in yourscript.php, put something like the following:
<?php
// load your userId (for example, with $_SESSION, but do what you want here)
$actualUser = $_SESSION['userId'];
// checks if the requested id to delete fits your actual current user's id
if (isset($_GET['currentUser'] && $_GET['currentUser'] == $actualUser)
{
$user = $_GET['currentUser'];
$file = 'user'.$user.'.php';
unlink($file);
}

Check certain URL in JavaScript?

How can I add something in JavaScript that will check the website URL of someone on a web site and then redirect to a certain page on the website, if a match is found? for example...
the string we want to check for, will be mydirectory, so if someone went to mysite.com/mydirectory/anyfile.php or even mysite.com/mydirectory/index.php JavaScript would then redirect their page / url to mysite.com/index.php because it has mydirectory in the URL, how can I do that using JavaScript?
If I have understood the question correctly, then it is fairly simple and can be achieved using document.URL
var search = 'mydirectory'; // The string to search for in the URL.
var redirect = 'http://mysite.com/index.php' // Where we will direct users if it's found
if(document.URL.substr(search) !== -1) { // If the location of
// the current URL string is any other than -1 (doesn't exist)
document.location = redirect // Redirect the user to the redirect URL.
}
Using document.URL you can check anything in the URL, however you might want to look into using something like Apache's mod_rewrite for redirecting the user before they even load the page.
Check out window.location, particularly it's properties and methods. You would be interested in (part of the) pathname property (you can split it on /) and the href property to change the page.
This is all assuming the javascript is being served in the first place; so I'm assuming anyfile.php and index.php would all result in the JS being served and not some 'generic 404' message.

How to get the title of a link using JavaScript

I want to get the title of a webpage without opening it, i.e. without using window.open().
I basically want to check whether the page i am providing the link for exists or an error is returned.
What I am trying is checking for similar links. Here is the code
(I want to know when to break out of this loop, i.e. at what point the link I am writing exists).
document.getElementById("TOI").innerHTML="<p>";
if (month<10) var m="0"+month;
else var m=month;
for(var i=1;;i++){
alert("ji");
var a="http://epaper.timesofindia.com/Repository/CAP/"+year+"/"+m+"/"+date+"/CAP_"+year+"_"+month+"_"+date+"_"+i+".pdf";
alert(a);
var link=window.open(a);
window.focus();
alert(link.location);
alert(link.document.title);
if(link.document.title!="The page cannot be found"){
link.close();
document.getElementById("TOI").innerHTML=document.getElementById("TOI").innerHTML+"<a href='http://epaper.timesofindia.com/Repository/CAP/"+year+"/"+m+"/"+date+"/CAP_"+year+"_"+month+"_"+date+"_"+i+".pdf' target=_blank>Page "+i+"</a> ";
}
else{link.close();break;}
}
document.getElementById("TOI").innerHTML=document.getElementById("TOI").innerHTML+"<\p>";
}
See to check if a url exists or not, you must use a server-side scripting language. Javascript is client-side and can't access server. So, first of all make a server side script (maybe php) that returns the status of url that you wanna check. Then from javascript side, use an ajax call to get the result of that script. That way you can check your url array, if all of them exists or not.
var attribute = element.getAttribute("title");
I want to get title of a webpage
without opening it(that is without
using window.open()) I basically want
to check whether the page i am
providing the link for exists or an
error is returned
Just because a page has a title doesn't mean it exists.
http://www.google.com/thispagedoesnotexist.htm
Examine HTTP status codes rather than page titles:
Can Prototype or JQuery return an HTTP status code on an AJAX request

Categories