JavaScript current URL check - javascript

I am wondering how I would get JavaScript to check if a user is on a certain URL so i can build an if statement from the result.
My reasoning is that if a user clicks on a link in the menu and they are currently on trucks.php the javascript will redirect them to a certain page. If they are not on trucks.php they will be directed to a different page.
Cheers guys.

The current location is in location.href.
The location object also contains some other useful fields:
location.hash: The part after the # in the URL
location.host: Hostname including port (if specified)
location.hostname: Just the hostname
location.pathname: The requested URI without protocol/host/port; starting with a /
location.port: The port - only if one is specified in the URL
location.protocol: Usually 'http:' or 'https:' - mind the colon at the end
In your case the most fail-safe way to check if the filename is trucks.php is this:
var parts = location.pathname.split('/');
if(parts[parts.length - 1] == 'trucks.php') {
location.href = 'some-other-page';
}
If you want to redirect without keeping the current page in history, use the following code instead of the location.href assignment:
location.replace('some-other-page');

Use window.location.href to get the current URL, or window.location.pathname to get just the path. For your specific problem, just the path name is required for the solution:
if (window.location.pathname == "/trucks.php")
window.location = "/somewhereelse.php";
Check out the MDC documentation for window.location.

Use window.location

Related

JQuery use value for location.href

How to I use a JQuery value for a url to use with location.href?
The url will be different every time the below url is an example.
The URL is stored in the database as
audit.php?audit=13957911461655047299&page=summary
Ajax is then used to retrieve the URL and save in a var called last_viewed so I would like to use the equivalent of
location.href = last_viewed
I have tried
location.href = '"'+last_viewed+'"'
but the URL becomes
http://www.x-rayqa.co.uk/"audit.php?audit=13957911461655047299&page=summary"
which obviously won't work because of the extra "s
if I try just
location.href = last_viewed
nothing happens, the script is broken.
If you don't add anything to the URL in your example, the browser assumes it's a relative URL and prefixes it with the current location origin (http://www.x-rayqa.co.uk on your site). If that stored link is on the same server, you'll need to ensure the path is correct after the server name.
If it's not local (i.e., an external link) then you'll have to add the server and protocol prefix yourself to make the link work. Take a look at the window.location documentation as well, which might help clear some things up.
https://developer.mozilla.org/en-US/docs/Web/API/Window.location
You can assign directly to window.location.href or use window.location.assign().

Window.location.href not works when url has # symbol in it

I have a popup call which takes the user credentials and login the user. Usully user would like to same page after login also. That's way I want to refresh the current page. I am using
window.location.href="currentrul";
This works just fine when we don't have # symbol in url. Let's say my URL is something like http://www.test.com/faq#shipping, it won't works. Any suggestions are appreciable.
Thanks in advance
If you want to refresh the page, use:
window.location.reload();
No, because # signifies an anchor on the same page.
The fragment identifier introduced by a hash mark # is the optional
last part of a URL for a document. It is typically used to identify a
portion of that document. The generic syntax is specified in RFC 3986.
The hash mark separator in URIs does not belong to the fragment
identifier.
Source: http://en.wikipedia.org/wiki/Fragment_identifier
try this:
var currentURL = window.location.href;
if(currentURL.indexOf('#') != -1){
currentURL = currentURL.substr(0, currentURL.indexOf('#'));
}
window.location.href = currentURL;

How do we update URL or query strings using javascript/jQuery without reloading the page?

Is there a way to update the URL programatically without reloading the page?
EDIT: I added something in the title in post .I just want to make it clear that I don't want to reload the page
Yes and no. All the common web browsers has a security measure to prevent that. The goal is to prevent people from creating replicas of websites, change the URL to make it look correct, and then be able to trick people and get their info.
However, some HTML5 compatible web browsers has implemented an History API that can be used for something similar to what you want:
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?myNewUrlQuery=1';
window.history.pushState({path:newurl},'',newurl);
}
I tested, and it worked fine. It does not reload the page, but it only allows you to change the URL query. You would not be able to change the protocol or the host values.
For more information:
http://diveintohtml5.info/history.html
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
Yes - document.location = "http://my.new.url.com"
You can also retrieve it the same way eg.
var myURL = document.location;
document.location = myURL + "?a=parameter";
The location object has a number of useful properties too:
hash Returns the anchor portion of a URL
host Returns the hostname and port of a URL
hostname Returns the hostname of a URL
href Returns the entire URL
pathname Returns the path name of a URL
port Returns the port number the server uses for a URL
protocol Returns the protocol of a URL
search Returns the query portion of a URL
EDIT:
Setting the hash of the document.location shouldn't reload the page, just alter where on the page the focus is. So updating to #myId will scroll to the element with id="myId". If the id doesn't exist I believe nothing will happen? (Need to confirm on various browsers though)
EDIT2: To make it clear, not just in a comment:
You can't update the whole URL with javascript without changing the page, this is a security restriction. Otherwise you could click on a link to a random page, crafted to look like gmail, and instantly change the URL to www.gmail.com and steal people's login details.
You can change the part after the domain on some browsers to cope with AJAX style things, but that's already been linked to by Osiris. What's more, you probably shouldn't do this, even if you could. The URL tells the user where he/she is on your site. If you change it without changing the page contents, it's becomes a little confusing.
You can use :
window.history.pushState('obj', 'newtitle', newUrlWithQueryString)
Use
window.history.replaceState({}, document.title, updatedUri);
To update Url without reloading the page
var url = window.location.href;
var urlParts = url.split('?');
if (urlParts.length > 0) {
var baseUrl = urlParts[0];
var queryString = urlParts[1];
//update queryString in here...I have added a new string at the end in this example
var updatedQueryString = queryString + 'this_is_the_new_url'
var updatedUri = baseUrl + '?' + updatedQueryString;
window.history.replaceState({}, document.title, updatedUri);
}
To remove Query string without reloading the page
var url = window.location.href;
if (url.indexOf("?") > 0) {
var updatedUri = url.substring(0, url.indexOf("?"));
window.history.replaceState({}, document.title, updatedUri);
}
Define a new URL object, assign it the current url, append your parameter(s) to that URL object and finally push it to your browsers state.
var url = new URL(window.location.href);
//var url = new URL(window.location.origin + window.location.pathname) <- flush existing parameters
url.searchParams.append("order", orderId);
window.history.pushState(null, null, url);
Yes
document.location is the normal way.
However document.location is effectively the same as window.location, except for window.location is a bit more supported in older browsers so may be the prefferable choice.
Check out this thread on SO for more info:
What's the difference between window.location and document.location in JavaScript?
Prefix URL changes with a hashtag to avoid a redirect.
This redirects
location.href += '&test='true';
This doesn't redirect
location.href += '#&test='true';
Plain javascript: document.location = 'http://www.google.com';
This will cause a browser refresh though - consider using hashes if you're in need of having the URL updated to implement some kind of browsing history without reloading the page. You might want to look into jQuery.hashchange if this is the case.
You'll need to be more specific. What do you mean by 'update the URL'? It could mean automatically navigating to a different page, which is certainly possible.
If you want to just update the contents of the address bar without reloading the page, see Modify the URL without reloading the page
Yes - document.location.hash for queries

How do I set window.location to a specific path (without a host)?

I am using the window location method to redirect a webpage to another after a set amount of time.
The url needs to change from www.myurl.com/home to www.myurl.com/other. The problem is that I do not know what the final URLs will be so I cannot use absolute links, they have to be a path only. This is what I have so far:
window.location.pathname = "mobility.html"
You can just prepend a / to your URL to make them relative to the domain root (without having to hardcode the domain name). Like this:
window.location = "/mobility.html"
window.location.assign("/path") also works.

Get the current url but without the http:// part bookmarklet!

Guys I have a question, hoping you can help me out with this one. I have a bookmarklet;
javascript:q=(document.location.href);void(open('http://other.example.com/search.php?search='+location.href,'_self ','resizable,location,menubar,toolbar,scrollbars,status'));
which takes URL of the current webpage and search for it in another website. When I use this bookmarklet it takes the whole URL including http:// and searches for it. But now I would like to change this bookmarklet so it will take only the www.example.com or just example.com (without http://) and search for this url. Is it possible to do this and can you please help me with this one?
Thank you!
JavaScript can access the current URL in parts. For this URL:
http://css-tricks.com/example/index.html
window.location.protocol = "http"
window.location.host = "css-tricks.com"
window.location.pathname = "/example/index.html"
please check: http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
This should do it
location.href.replace(/https?:\/\//i, "")
Use document.location.host instead of document.location.href. That contains only the host name and not the full URL.
Use the URL api
A modern way to get a part of the URL can be to make a URL object from the url that you are given.
const { hostname } = new URL('https://www.some-site.com/test'); // www.some-site.com
You can of course just pass window location or any other url as an argument to the URL constructor.
Like this
const { hostname } = new URL(document.location.href);
Do you have control over website.com other.example.com? This should probably be done on the server side.
In which case:
preg_replace("/^https?:\/\/(.+)$/i","\\1", $url);
should work. Or, you could use str_replace(...), but be aware that that might strip 'http://' from somewhere inside the URL:
str_replace(array('http://','https://'), '', $url);
EDIT: or, if you just want the host name, you could try parse_url(...)?
Using javascript replace via regex matching:
javascript:q=(document.location.href.replace(/(https?|file):\/\//,''));void(open('http://website.com/search.php?search='+q,'_self ','resizable,location,menubar,toolbar,scrollbars,status'));
Replace (https?|file) with your choice, e.g. ftp, gopher, telnet etc.

Categories

Resources