JavaScript: Detect user manual refresh request in web page - javascript

I am designing a HTML page, and I would like to send a simple message (or trigger some action) when the user intentionally request updating (update button on the web browser, pressing F5... or whatever any other manual method that could exist) of the HTML file.
Something like:
window.onmanualupdaterequest = alert("You requested update");
Or whatever the correct procedure could be.
How could I do this?
Further notes:
I have tried the window.onbeforeunload function (example), but it does not exactly solve the problem (I would say it has not the same behavior as user request).
I would like to ignore the autoupdate case (like in setInterval or similar functions or scripts) from the manual update case. This question is about the manual one.
The classical Android swipe-down update method for a web page is considered here as a manual update method.

My idea would be to use the sessionStorage to save the window.location.href on pageload. If the user reloads the page the stored location should match the current url:
window.addEventListener('load', function () {
const lastUrl = sessionStorage.getItem('lastUrl');
if(lastUrl && lastUrl === window.location.href) {
alert("You requested update");
}
sessionStorage.setItem('lastUrl', window.location.href);
});

Related

javascript check which URL loaded and give notification

I'm trying to find a way in javascript to check which URL is loaded, then have a popup notifying the user to update their old bookmarket and have it redirect to the new location in a few seconds.
For example, the url maybe Http:\abc\myappage and I want to check if they are on the http:\abc site which if they are, the notification pops up and redirects them.
Currently I have a simple redirect to take them to the new site, but I never considered anyone that has an old bookmark which would never get updated if you don't inform them about the change.
Thanks.
You can access the current url from within JavaScript with window.location.
Using window.location you can access the current domain and path, then by setting window.location.href = 'your new site' after a few seconds or after some user interaction will cause the browser to navigate to the supplied url.
if(window.location.host === 'abc'){
alert('This url is no longer valid.');
window.location.href = 'http://abc/myappage
}
You can use window.location to get some information regarding the current url:
window.location.origin in the console on this current page, prints:
"http://stackoverflow.com"
Then you could run some JS logic to check against your other url and use alert() to crete the pop up.
working JSBIN: https://jsbin.com/gijola/edit?js,console
adding code:
function checker (url) {
var here = window.location.origin;
l(here);
if (here !== 'whatever you want to check') {
alert('please update your bookmark!!');
}
}

JavaScript browser navbar event

I want to prevent users to navigate to URL´s that are not accessed through html element. Example:
Actually navigating on: myweb.com/news
And I want to navigate to myweb.com/news?article_id=10 by writing this in the browser navigation bar to avoid pressing any element (like <a>).
When the user writes myweb.com/news?article_id=10 in the browser url, at the moment he presses enter, the browser should not allow him to navigate to the url.
I have tried:
//This wont work since jquery does not support it
$(window.location.href).on('change', function() {
//Here check if href contains '?'
alert("Not allowed");
});
//Neither works, doesnt do anything
$(window).on('change', function() {
alert("Not allowed");
});
References:
there is something similar asked here On - window.location.hash - Change?, but im interested in the 'parameter' version of that question.
There are some known solutions :
) Each time a user click a link - you save the page value to a cookie.
Later , at the server- you check that interval ( value-1 ... value+1).
) You can also save to a hidden field and check that value in the server.
So let's say a user is on page 3. ( the server serve that page - so a cookie/hidden value with value 3 is exists)
now he tries to go to page 10 :
you - in the server side - reads the cookie + requested Page number. if the interval is bigger than 1 - then you deny that request.
Try adding an event listener:
window.addEventListener('popstate', function(event)
{
var location = document.location;
var state = JSON.stringify(event.state);
});
To check the URL, The best thing would be to match it against a regex like:
if (url.match(/\?./)) {
// do not allow access
}
You might need to extend this, depending on other URL's that you need to forbid access to.

Using window.history.back() to navigate to a certain page?

Is it possible to use window.history.back() to navigate back to a particular page? Like an index.php page? I ask because the way my setup is, some users may have to be directed back 2 pages while others might have to only be directed back one page (depending on more complicated things), but they will all have to be directed back to the same index.php page. So, is this possible?
window.history.go(); let you specify how many pages you want to go back or forward in the browser session history.
https://developer.mozilla.org/en-US/docs/Web/API/History#Methods
If you keep a breadcrumb trail, you'll know the correct number needed… although there might be a better way to do this.
It turns out to be that in chrome particularly in version 105.0.5195.127 the browser appends previous page's url, aka 'https://yourdomain.com/foo/bar' instead of 'https://yourdomain.com/bar' into your next page while pushing state as if
window.history.pushState((null, null, '/bar')
And I suggest to include the full url in order to handle any url case
export async function pushHistoryState(url)
{
try {
console.log('History state URL:' + url);
let loc = `${location.protocol}//${location.host}/`;
window.history.pushState({ prevUrl: window.location.href }, null, loc + url);
} catch(e) {
console.log(e);
}
}
window.history.state.prevUrl now contains previous URL
useful links: https://stackoverflow.com/a/56184390/6897369 Back button / backspace does not work with window.history.pushState How to get the previous URL in JavaScript? Why does my history.pushState call result in a null state? How to add or append new stateObject to history window.history.pushState change url without removing last part window.history.pushState not working for a second time

Facebook Changes Page URL but does not actually change page

I was on Facebook and realised that when I change page the page address changes but the page does not redirect but loads via ajax instead.
You can tell because the console does not clear when you click the link but the URL changes.
Weird, but anyone know how it is done?
Facebook runs with massive AJAX calls that changes the page state and the sections.
So to make a page linkable to somebody by copying the URL address, every time you call an AJAX relevant function they updates the URL using a fake anchor "#!" plus the real address.
Simply when you load the real page (using F5 or linking that so somebody) a JS parser catchs the string after #! (if there is) and redirect you to baseaddress + that.
I belive something like this (untested):
var urlstr = new String(location.href);
var urlparm = urlstr.split('#!');
var last = urlparm.length - 1;
if( (urlparm[last] != urlparm[0]) && (urlparm[last] != "/") )
{ var redir = "http://www.facebook.com" + urlparm[last];
location.href = redir;
}
In Google Chrome instead the URL really changes, I'm according that there is an hash somewhere, but I don't know where and how.

Read window.location.hash servlet-side not possible?

In my web app, a user can click an item in a list, and I modify the url in their browser:
<li>Horse</li>
<li>Cow</li>
<li>Goat</li>
function onListItemClicked() {
window.location.hash = item.name;
}
this will change the url in the user's browser to:
www.example.com#Horse
www.example.com#Cow
www.example.com#Goat
if I'm reading correctly, we can't get the # part of the url servlet-side, right? If the user copies and pastes the url from their browser to friend, it would be cool if I could generate the page already initialized with the item they clicked.
It looks like this is not possible, I'll have to load the appropriate page via javascript after the document finishes loading,
Thanks
No, you can't do this from the server side on. URL fragments are purely client side. You need to do this in the client side during page load.
window.onload = function() {
var hash = window.location.hash;
// Do your business thing here based on the hash.
}

Categories