JavaScript browser navbar event - javascript

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.

Related

JavaScript: Detect user manual refresh request in web page

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);
});

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!!');
}
}

polling for RSS feed with casperjs not working

I am trying to match a token (string token) in the RSS feed using casperjs waitFor() but it does not seem to work. There are other ways (not using polling) to get around but I need to poll for it. Here is the code snippet:
casper.then(function() {
this.waitFor(function matchToken() {
return this.evaluate(function() {
if(!this.resourceExists(token)) {
this.reload();
return false;
}
return true;
});
});
});
The updates to rss url are not dynamic and hence, a refresh would be needed to check for the token. But it seems (from the access log) that I am not getting any hits (reload not working) on the rss url. Ideally, I would want to refresh the page if it doesn't see the token and then check for the token again & it should keep doing that until the waitFor times out.
I also tried using assertTextExists() instead of resourceExists() but even that did not work.
I am using PhantomJS (1.9.7) & the url is: https://secure.hyper-reach.com:488/rss/323708
The token I am looking for is --> item/272935. If you look at the url I have mentioned above, you will find this in a each guid tag. The reason why I am including "item/" also as a part of my token is so that it doesn't match any other numbers incorrectly.
evaluate() is the sandboxed page context. Anything inside of it doesn't have access to variables defined outside and this refers to window of the page and not casper. You don't need the evaluate() function here, since you don't access the page context.
The other thing is that casper.resourceExists() works on the resource meta data such as URL and request headers. It seems that you want to check the content of the resource. If you used casper.thenOpen() or casper.open() to open the RSS feed, then you can check with casper.getPageContent(), if the text exists.
The actual problem with your code is that you mix synchronous and asynchronous code in a way that won't work. waitFor() is the wrong tool for the job, because you need to reload in the middle of its execution, but the check function is called so fast that there probably won't be a complete page load to actually test it.
You need to recursively check whether the document is changed to your liking.
var tokenTrials = 0,
tokenFound = false;
function matchToken(){
if (this.getPageContent().indexOf(token) === -1) {
// token was not found
tokenTrials++;
if (tokenTrials < 50) {
this.reload().wait(1000).then(matchToken);
}
} else {
tokenFound = true;
}
}
casper.then(matchToken).then(function(){
test.assertTrue(tokenFound, "Token was found after " + tokenTrials + " trials");
});

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.

Click ID and open URL?

I am trying to click on a #ID and open a URL - but [as a newbie] - I can't seem to get it. I am using
$('#Test').click(function() {
OpenUrl('some url');
return false;
});
Something like:
$("#Test").click(function(event){
window.location.href = "some url";
event.preventDefault();
});
Just use window.location = 'some url'
$('#Test').click(function() {
window.location = 'http://www.google.com'
return false;
});
To elaborate a bit, window.location is an object with different quite interesting properties, you can read more about it here. In short, it contains the following properties (quoted from the link):
Property Description Example
hash the part of the URL that follows the #test
# symbol, including the # symbol.
host the host name and port number. [www.google.com]:80
hostname the host name (without the port number www.google.com
or square brackets).
href the entire URL. http://[www.google.com]:80
/search?q=devmo#test
pathname the path (relative to the host). /search
port the port number of the URL. 80
protocol the protocol of the URL. http:
search the part of the URL that follows the ?q=devmo
? symbol, including the ? symbol.
Since window.location is an object, it can also contain methods, which window.location does. By using these methods, instead of just assigning a string to the object, you can exert greater control of how the page is loaded, i.e. force a reload from the server or allow the browser to use a cached entry, skip creating a new history point etc.
Here is an overview of available methods:
Method Description
assign(url) Load the document at the provided URL.
reload(forceget) Reload the document from the current URL. forceget is a
boolean, which, when it is true, causes the page to always
be reloaded from the server. If it is false or not specified,
the browser may reload the page from its cache.
replace(url) Replace the current document with the one at the provided
URL. The difference from the assign() method is that after
using replace() the current page will not be saved in
session history, meaning the user won't be able to use
the Back button to navigate to it.
toString() Returns the string representation of the Location object's
URL.
You can also open resources in new windows if you want to. Please be aware that some users dislike having links opened in new windows for them, and prefer to having to consciously make this decision themselves. What you can do, however, is to mimic some of this functionality in your click-handler and try to figure out which mouse-button was clicked. If it was the middle-mouse button, then most browsers would open the link in a new window. This won't be exactly the same, since users won't be able to right-click and select 'Open in new window', but it might be good enough. Anyway, here's how to open a resource in a new window:
var WindowObjectReference;
function openRequestedPopup()
{
WindowObjectReference = window.open(
"http://www.domainname.ext/path/ImageFile.png",
"DescriptiveWindowName",
"resizable=yes,scrollbars=yes,status=yes");
}
You can read a lot more information here
hm if your OpenUrl function looks anything like this this should work just fine :D
function OpenUrl(url){
window.location = url;
}
btw: why returning false on click??

Categories