How do I get the referrer's domain/host name using JavaScript? - javascript

I know I can get the host name of the current page, by simply doing:
var myhostname = location.hostname;
But how do I get the host name of the referrer? I can get the referrer by
var referrer = document.referrer;
but unfortunately there's no document.referrer.hostname available in JavaScript. How can I get this value?
An example of where this is useful is if somebody clicks a link on google.com. I want to be able to retrieve google.com from the referrer (not the page and the query string).

This would do:
document.referrer.split('/')[2];
Example.

function parseURL(url) {
var a=document.createElement('a');
a.href=url;
return a.hostname;
}
This is a relatively old question, nevertheless this may help any followers.

By parsing it. document.referrer.split( '/' ); will get you close. Or take a look at this
http://blog.stevenlevithan.com/archives/parseuri
If referrer is coming from a browser, it will be sane -- but just in case you want more robust parsing.

You can use var referrer = new URL(document.referrer).hostname.
See https://developer.mozilla.org/en-US/docs/Web/API/URL.URL.

You can use regexp to extract this data.
string.match(/^http([s]?)://([a-zA-Z0-9-_\.]+)(:[0-9]+)?/);

Hi use this function to get domain name.
function getDomain(url) {
if (url) {
var match = /(?:https?:\/\/)?(?:\w+:\/)?[^:?#\/\s]*?([^.\s]+\.(?:[a-z]{2,}|co\.uk|org\.uk|ac\.uk|org\.au|com\.au))(?:[:?#\/]|$)/gi
.exec(url);
return match ? match[1] : null;
} else
return null;
}

It includes the protocol, but document.origin will work. It works via the Origin header, which has no path information included with it.

Related

JS: get hostname from url , regex not working

I am trying to get hostname from set of urls that my webapp can encounter with.
The desired output should be something like http://localhost/Webapp/, ending at /Webapp/ and everything after that should be removed.
Kindly note that I dont want to use word Webapp in regex as this name is dynamic and used for demo/testcase only.this can be anything , not harcoded.
In real example I am using location.href.replace(/index.+/g, "").replace(/#.+/g, "")
and I want to keep only hostname ending atWebapp/.
Problem:
my solution seems to working fine except "http://localhost/Webapp/#" is not working correctly ? why is that ? see fiddle below
JSFIDDLE: http://jsfiddle.net/bababalcksheep/um0uqb8v/
JS:
var getHost = function (url) {
return url.replace(/index.+/g, "").replace(/#.+/g, "")
};
var urls = [
"http://localhost/Webapp/",
"http://localhost/Webapp/#",
"http://localhost:8080/Webapp/#sdf#dfgdf#fdg",
"12.168.1.1:8080/Webapp/index.html#",
"https://localhost/Webapp/index.html#ab#bg",
"https://localhost/Webapp/index.html"
];
//Print all urls
$.each(urls, function () {
$("<p/>").text(getHost(this)).appendTo($(".test"));
});
Use url.match(/https?:\/\/([^\/]+)/);
EDIT:
It returns an array where the 1st element is the host with protocol and the 2nd without.
You can try removing anything after the last slash (files and hash-es):
var getHost = function (url) {
return url.replace(/\/[^/]*?$/, '/');
};
And here's the updated fiddle.
There's a bit of a trick you can use to get the browser to extract the hostname for you.
var getHost = function (url) {
var a = document.createElement('a');
a.href = url;
return a.hostname;
};
It also appears you want the path as well. You can access it with the pathname property of the a element. If you're doing that, you ought to rename the function to something like getHostAndPath().

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;

How to use location object to parse URL without redirecting the page in javascript?

The browser has a very efficient URL parser that let you get location.href, hash, query, etc from the current URL. I'd like to use it instead of coding something using regexes.
If you set location.href or do location.replace(url), the page gets redirected in Chrome. I tried to get the prototype of location in this browser, but I can't find location.prototype. There is a location.__proto__ which is described as the Location class in the js console, but I can't find a way to instantiate it. Plus, I need a cross browser solution and __proto__ is not available in IE.
If it's not possible, don't give me a regex alternative, just tell me the hard truth, provided you can back it up with evidences.
Yes, it's very much possible! If you create a new a object, you can use the location fields without redirecting the browser.
For instance:
var a = document.createElement('a');
a.href = "http://openid.neosmart.net/mqudsi#fake"
You can now access .hash, .pathname, .host, and all the other location goodies!
> console.log(a.host);
openid.neosmart.net
I wrote a generalized version of the wonderful Mahmoud solution:
var parseUrl = (function(){
var div = document.createElement('div');
div.innerHTML = "<a></a>";
return function(url){
div.firstChild.href = url;
div.innerHTML = div.innerHTML;
return div.firstChild;
};
})();
It works that way:
var url = parseUrl('http://google.com');
var url = zerobin.parseUrl('http://google.com');
console.log(url.protocol);
"http:"
console.log(url.host);
"google.com"
The parseUrl code is a bit complicated because IE requires the link HTML code to be processed by its HTML parser if you want it to parse the URL. So we create a closure in which we store a <div> with a <a> as child (avoid recreating it a each call), and when we need URL parsing, we just take the HTML of div, and inject it back to itself, forcing IE to parse it.

Get relative path of the page url using javascript

In javascript, how can I get the relative path of the current url?
for example http://www.example.com/test/this?page=2
I want just the /test/this?page=2
Try
window.location.pathname+window.location.search
location.href
holds the url of the page your script is running in.
The quickest, most complete way:
location.href.replace(/(.+\w\/)(.+)/,"/$2");
location.href.replace(location.origin,'');
Only weird case:
http://foo.com/ >> "/"
You can use the below snippet to get the absolute url of any page.
var getAbsoluteUrl = (function() {
var a;
return function(url) {
if(!a) a = document.createElement('a');
a.href = url;
return a.href;
}
})();
// Sample Result based on the input.
getAbsoluteUrl('/'); //Returns http://stackoverflow.com/
Checkout get absolute URL using Javascript for more details and multiple ways to achieve the same functionality.
I use this:
var absURL = document.URL;
alert(absURL);
Reference: http://www.w3schools.com/jsref/prop_doc_url.asp
You should use it the javascript way, to retrieve the complete path including the extensions from the page,
$(location).attr('href');
So, a path like this, can be retrieved too.
www.google.com/results#tab=2

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