window.location.indexOf not working in Javascript - javascript

Below is what I have.
var myString = "http://localhost:8888/www.smart-kw.com/";
alert(myString.indexOf("localhost"));
This give me alert... however if I change var myString = "http://localhost:8888/www.smart-kw.com/"; to var myString = window.location;, it won't work (I don't get alert).
var myString = window.location;
alert(myString.indexOf("localhost"));

window.location is an accessor property, and getting its value gives you an object, not a string, and so it doesn't have an indexOf function. (It's perfectly understandable that people sometimes think it's a string, since when you set its value, the accessor property's setter accepts a string; that is, window.location = "some url"; actually works. But when you get it, you don't get a string.)
You can use window.location.toString(), String(window.location), or window.location.href to get a string for it if you like, or use any of its various properties to check specifics. From the link, given example url http://www.example.com:80/search?q=devmo#test:
hash: The part of the URL that follows the # symbol, including the # symbol. You can listen for the hashchange event to get notified of changes to the hash in supporting browsers.Example: #test
host: The host name and port number.Example: www.example.com:80
hostname: The host name (without the port number).Example: www.example.com
href: The entire URL.Example: http://www.example.com:80/search?q=devmo#test
pathname: The path (relative to the host).Example: /search
port: The port number of the URL.Example: 80
protocol: The protocol of the URL.Example: http:
search: The part of the URL that follows the ? symbol, including the ? symbol.Example: ?q=devmo
For instance, for your quoted example, you might check window.location.hostname === "localhost".

As far as I know window.location is a Location object.
For instance, window.location.href will give you the entire URL.
var url = window.location.href;
alert(url.indexOf("domain"));
But this kind of check is bound to trigger false-positives. You are better using window.location.hostname property which holds the host name part.
var hostname = window.location.hostname;
alert(hostname === "my.domain.com");

I found a way to make this work:
(window.location.href).indexOf("localhost") > -1)
I actually use this for my projects as conditionals and it works just fine.

Related

window location get the URL [duplicate]

All I want is to get the website URL. Not the URL as taken from a link. On the page loading I need to be able to grab the full, current URL of the website and set it as a variable to do with as I please.
Use:
window.location.href
As noted in the comments, the line below works, but it is bugged for Firefox.
document.URL
See URL of type DOMString, readonly.
URL Info Access
JavaScript provides you with many methods to retrieve and change the current URL, which is displayed in the browser's address bar. All these methods use the Location object, which is a property of the Window object. You can read the current Location object by reading window.location:
var currentLocation = window.location;
Basic URL Structure
<protocol>//<hostname>:<port>/<pathname><search><hash>
protocol: Specifies the protocol name be used to access the resource on the Internet. (HTTP (without SSL) or HTTPS (with SSL))
hostname: Host name specifies the host that owns the resource. For example, www.stackoverflow.com. A server provides services using the name of the host.
port: A port number used to recognize a specific process to which an Internet or other network message is to be forwarded when it arrives at a server.
pathname: The path gives info about the specific resource within the host that the Web client wants to access. For example, /index.html.
search: A query string follows the path component, and provides a string of information that the resource can utilize for some purpose (for example, as parameters for a search or as data to be processed).
hash: The anchor portion of a URL, includes the hash sign (#).
With these Location object properties you can access all of these URL components and what they can set or return:
href - the entire URL
protocol - the protocol of the URL
host - the hostname and port of the URL
hostname - the hostname of the URL
port - the port number the server uses for the URL
pathname - the path name of the URL
search - the query portion of the URL
hash - the anchor portion of the URL
origin - the window.location.protocol + '//' + window.location.host
I hope you got your answer..
Use window.location for read and write access to the location object associated with the current frame. If you just want to get the address as a read-only string, you may use document.URL, which should contain the same value as window.location.href.
Gets the current page URL:
window.location.href
OK, getting the full URL of the current page is easy using pure JavaScript. For example, try this code on this page:
window.location.href;
// use it in the console of this page will return
// http://stackoverflow.com/questions/1034621/get-current-url-in-web-browser"
The window.location.href property returns the URL of the current page.
document.getElementById("root").innerHTML = "The full URL of this page is:<br>" + window.location.href;
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript</h2>
<h3>The window.location.href</h3>
<p id="root"></p>
</body>
</html>
Just not bad to mention these as well:
if you need a relative path, simply use window.location.pathname;
if you'd like to get the host name, you can use window.location.hostname;
and if you need to get the protocol separately, use window.location.protocol
also, if your page has hash tag, you can get it like: window.location.hash.
So window.location.href handles all in once... basically:
window.location.protocol + '//' + window.location.hostname + window.location.pathname + window.location.hash === window.location.href;
//true
Also using window is not needed if already in window scope...
So, in that case, you can use:
location.protocol
location.hostname
location.pathname
location.hash
location.href
To get the path, you can use:
console.log('document.location', document.location.href);
console.log('location.pathname', window.location.pathname); // Returns path only
console.log('location.href', window.location.href); // Returns full URL
Open Developer Tools, type in the following in the console and press Enter.
window.location
Ex: Below is the screenshot of the result on the current page.
Grab what you need from here. :)
Use: window.location.href.
As noted above, document.URL doesn't update when updating window.location. See MDN.
Use window.location.href to get the complete URL.
Use window.location.pathname to get URL leaving the host.
You can get the current URL location with a hash tag by using:
JavaScript:
// Using href
var URL = window.location.href;
// Using path
var URL = window.location.pathname;
jQuery:
$(location).attr('href');
For complete URL with query strings:
document.location.toString()
For host URL:
window.location
// http://127.0.0.1:8000/projects/page/2?name=jake&age=34
let url = new URL(window.location.href);
/*
hash: ""
host: "127.0.0.1:8000"
hostname: "127.0.0.1"
href: "http://127.0.0.1:8000/projects/page/2?username=jake&age=34"
origin: "http://127.0.0.1:8000"
password: ""
pathname: "/projects/page/2"
port: "8000"
protocol: "http:"
search: "?name=jake&age=34"
username: ""
*/
url.searchParams.get('name')
// jake
url.searchParams.get('age')
// 34
url.searchParams.get('gender')
// null
To get the path, you can use:
http://www.example.com:8082/index.php#tab2?foo=789
Property Result
------------------------------------------
window.location.host www.example.com:8082
window.location.hostname www.example.com
window.location.port 8082
window.location.protocol http:
window.location.pathname index.php
window.location.href http://www.example.com:8082/index.php#tab2
window.location.hash #tab2
window.location.search ?foo=789
window.location.origin https://example.com
var currentPageUrlIs = "";
if (typeof this.href != "undefined") {
currentPageUrlIs = this.href.toString().toLowerCase();
}else{
currentPageUrlIs = document.location.toString().toLowerCase();
}
The above code can also help someone
Adding result for quick reference
window.location;
Location {href: "https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript",
ancestorOrigins: DOMStringList,
origin: "https://stackoverflow.com",
replace: ƒ, assign: ƒ, …}
document.location
Location {href: "https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript",
ancestorOrigins: DOMStringList,
origin: "https://stackoverflow.com",
replace: ƒ, assign: ƒ
, …}
window.location.pathname
"/questions/1034621/get-the-current-url-with-javascript"
window.location.href
"https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript"
location.hostname
"stackoverflow.com"
For those who want an actual URL object, potentially for a utility which takes URLs as an argument:
const url = new URL(window.location.href)
https://developer.mozilla.org/en-US/docs/Web/API/URL
Nikhil Agrawal's answer is great, just adding a little example here you can do in the console to see the different components in action:
If you want the base URL without path or query parameter (for example to do AJAX requests against to work on both development/staging AND production servers), window.location.origin is best as it keeps the protocol as well as optional port (in Django development, you sometimes have a non-standard port which breaks it if you just use hostname etc.)
You have multiple ways to do this.
1:
location.href;
2:
document.URL;
3:
document.documentURI;
Use this:
var url = window.location.href;
console.log(url);
In jstl we can access the current URL path using pageContext.request.contextPath. If you want to do an Ajax call, use the following URL.
url = "${pageContext.request.contextPath}" + "/controller/path"
Example: For the page http://stackoverflow.com/posts/36577223 this will give http://stackoverflow.com/controller/path.
The way to get the current location object is window.location.
Compare this to document.location, which originally only returned the current URL as a string. Probably to avoid confusion, document.location was replaced with document.URL.
And, all modern browsers map document.location to window.location.
In reality, for cross-browser safety, you should use window.location rather than document.location.
location.origin+location.pathname+location.search+location.hash;
and
location.href
does the same.
You can get the full link of the current page through location.href
and to get the link of the current controller, use:
location.href.substring(0, location.href.lastIndexOf('/'));
Short
location+''
let url = location+'';
console.log(url);
Getting the current URL with JavaScript :
window.location.toString();
window.location.href
if you are referring to a specific link that has an id this code can help you.
$(".disapprove").click(function(){
var id = $(this).attr("id");
$.ajax({
url: "<?php echo base_url('index.php/sample/page/"+id+"')?>",
type: "post",
success:function()
{
alert("The Request has been Disapproved");
window.location.replace("http://localhost/sample/page/"+id+"");
}
});
});
I am using ajax here to submit an id and redirect the page using window.location.replace. just add an attribute id="" as stated.
let url = new URL(window.location.href);
console.log(url.href);
Use the above code to get the current URL of the website.
or try this - https://bbbootstrap.com/code/get-current-url-javascript-54628697
Firstly check for page is loaded completely in
browser,window.location.toString();
window.location.href
then call a function which takes url, URL variable and prints on console,
$(window).load(function(){
var url = window.location.href.toString();
var URL = document.URL;
var wayThreeUsingJQuery = $(location).attr('href');
console.log(url);
console.log(URL);
console.log(wayThreeUsingJQuery );
});

Ensure URL is relative before navigating via JavaScript's location.replace()

I have a login page https://example.com/login#destination where destination is the target URL the user was trying to navigate to when they were required to log in.
(i.e. https://example.com/destination)
The JavaScript I was thinking about using was
function onSuccessfulLogin() {
location.replace(location.hash.substring(1) || 'default')
}
This would result in an XSS vulnerability, by an attacker providing the link
https://example.com/login#javascript:..
Also I need to prevent navigation to a lookalike site after login.
https://example.com/login#https://looks-like-example.com
or https://example.com/login#//looks-like-example.com
How can I adjust onSuccessfulLogin to ensure the URL provided in the hash # portion is a relative URL, and not starting with javascript:, https:, // or any other absolute navigation scheme?
One thought is to evaluate the URL, and see if location.origin remains unchanged before navigating. Can you suggest how to do this, or a better approach?
From OWASP recommendations on Preventing Unvalidated Redirects and Forwards:
It is recommended that any such destination input be mapped to a value, rather than the actual URL or portion of the URL, and that server side code translate this value to the target URL.
So a safe approach would be mapping some keys to actual URLs:
// https://example.com/login#destination
var keyToUrl = {
destination: 'https://example.com/destination',
defaults: 'https://example.com/default'
};
function onSuccessfulLogin() {
var hash = location.hash.substring(1);
var url = keyToUrl[hash] || keyToUrl.defaults;
location.replace(url);
}
You could also consider providing only path part of the URL and appending it with a hostname in the code:
// https://example.com/login#destination
function onSuccessfulLogin() {
var path = location.hash.substring(1);
var url = 'https://example.com/' + path;
location.replace(url);
}
I would stick to the mapping though.
That is a very good point about the XSS vulnerability.
I believe all protocols only use English alphabetic characters, so a regex like /^[a-z]+:/i would check for those. Alternately if we're feeling more inclusive, /^[^:\/?]+:/ allows anything but a / or ? followed by a :. Then we can combine that with /^\/\/ to test for a protocol-free URL, which gives us:
// Either
var rexIsProtocol = /(?:^[a-z]+:)|(?:^\/\/)/i;
// Or
var rexIsProtocol = /(?:^[^:\/?]+:)|(?:^\/\/)/i;
Then the test is like this:
var url = location.hash.substring(1).trim(); // trim to deal with whitespace
if (rexIsProtocol.test(url)) {
// It starts with a protocol
} else {
// It doesn't
}
That said, the only one I think you need to be particularly bothered by is the javascript: pseudo-protcol, so you might just test for that.

Perfect URL Checking Regular Expression for MOST URL's

I am working on a project where I need to validate my URL's and stumbled upon the following RegEx pattern;
/(((http|ftp|https):\/{2})+(([0-9a-z_-]+\.)+(aero|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mn|mn|mo|mp|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|nom|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ra|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw|arpa)(:[0-9]+)?((\/([~0-9a-zA-Z\#\+\%#\.\/_-]+))?(\?[0-9a-zA-Z\+\%#\/&\[\];=_-]+)?)?))\b/imuS$/ # https://mathiasbynens.be/demo/url-regex
Which allows me to check URL's that always had a protocol before it (http, https or ftp). I would like to also allow the user to leave out the protocol and it still be valid. How do I do this?
Are there any other RegEx patterns that are better/more accurate that I can use to validate my URL's? Thanks for all answers!
I'm currently working a module that validates inputs. One of the validations required me to parse domains ( hostnames ) per:
RFC 952
RFC 1123
Trailing dots in domain names
To validate a domain I took a few steps, one of them was to use the
browser parsing logic by using this cool trick:
function parseURI( str ) {
var a = document.createElement( "a" );
// If the string doesn't contain a protocol, the browser
// will default to the current document location.
a.href = /^(https?:\/\/)/i.test( str ) === false ? ( "http://" + str ) : str;
// Since I can't overwrite a[property] - return an object I control ( Muahahah ).
return {
hash: a.hash,
hostname: a.hostname,
href: a.href,
origin: a.origin,
pathname: a.pathname,
port: a.port,
protocol: a.protocol,
search: a.search,
// When parsing the URL by the browser fails, the browser will
// set the hostname based on the current document.location value.
valid: a.hostname !== document.location
}
}
If validating a hostname | domain is what you are after, I can share my insights on the topic as well.
I suggest you to use regex powers in your regex for extension part like this:
(aero|asia|arpa|a[c-gil-oq-uwxz]|biz|b[abd-jmnorstv-z]|cat|com|coop|c[acdf-ik-oruvxyz]|
d[ejkmoz]|edu|e[cegr-u]|f[ijkmor]|gov|g[abd-ilmnp-uwy]|h[kmnrtu]|info|int|i[del-oq-t]|
jobs|j[emop]|k[eghimnprwyz]|l[abcikr-vy]|mil|mobi|museum|m[acdeghklnopr-z]|
name|net|nom|n[acefgilopruz]|org|pro|p[ae-hk-nrstwy]|qa|r[easuw]|s[a-eg-ortuvyz]|
tel|travel|t[cdfghj-prtvwz]|u[agksyz]|v[aceginu]|w[fs]|y[etu]|z[amw])
I modified it to the following so that the user can leave out the protocol;
/(((http|ftp|https):\/{2})?(([0-9a-z_-]+\.)+(aero|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mn|mn|mo|mp|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|nom|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ra|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw|arpa)(:[0-9]+)?((\/([~0-9a-zA-Z\#\+\%#\.\/_-]+))?(\?[0-9a-zA-Z\+\%#\/&\[\];=_-]+)?)?))\b$/
by making the first part (the protocol) optional using the ? operator.
http://www.regexr.com/ is a great tool to use for testing RegEx patterns and learning about how they work.

How can I get everything after the forward slash in my url?

When I visit my url, my script will get the current URL and store it in a variable with
var currentURL = (document.URL);
I'd like to get everything after the forward slash in my url because there will be a hash ID after the forward slash like this:
www.mysite.com/XdAs2
so this is what would be stored in my variable currentURL and I'd like to take only the XdAs2 from it and store that into another variable. In addition, I'd like to know two other things.
Is document.URL the best way to get the current URL or will I have issues with some browsers?
If I were to try to open that URL using an iframe, will document.URL still work? or must there be an address bar present containing the url? I would really appreciate answers for those questions three questions. Thank you
Here's some pseudo code:
var currentURL = (document.URL); // returns http://myplace.com/abcd
var part = currentURL.split("/")[1];
alert(part); // alerts abcd
Basically:
1) document.URL should work fine in all major browsers. For more info refer to this Mozilla Developer Network article or this SO question
2) for an iframe, you need to write something like: document.getElementById("iframe_ID").src.toString()
Using jquery, you can do he following in order to access every inch of the current URL:
www.mysite.com/XdAs2?x=123
assuming you have the following url:
1- get the url in a jQuery object
var currentUrl = $(location)
2- access everything using the following syntax
var result = currentUrl.attr('YOUR_DESIRED_PROPERTY');
some common properties:
hostname => www.mysite.com
pathname => XdAs2
search => ?x=123
I hope this may help.
If you want everything after the host, use window.location.pathname
Following on from Mohammed's answer you can do the same thing in vanilla javascript:
var urlPath = location.pathname,
urlHost = location.hostname;

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