location.host vs location.hostname and cross-browser compatibility? - javascript

Which one of these is the most effective vs checking if the user agent is accessing via the correct domain.
We would like to show a small js based 'top bar' style warning if they are accessing the domain using some sort of web proxy (as it tends to break the js).
We were thinking about using the following:
var r = /.*domain\.com$/;
if (r.test(location.hostname)) {
// showMessage ...
}
That would take care of any subdomains we ever use.
Which should we use host or hostname?
In Firefox 5 and Chrome 12:
console.log(location.host);
console.log(location.hostname);
.. shows the same for both.
Is that because the port isn't actually in the address bar?
W3Schools says host contains the port.
Should location.host/hostname be validated or can we be pretty certain in IE6+ and all the others it will exist?

As a little memo: the interactive link anatomy
--
In short (assuming a location of http://example.org:8888/foo/bar#bang):
hostname gives you example.org
host gives you example.org:8888

host just includes the port number if there is one specified. If there is no port number specifically in the URL, then it returns the same as hostname. You pick whether you care to match the port number or not. See https://developer.mozilla.org/en-US/docs/Web/API/Location for more info on the window.location object and the various choices it has for matching (with or without port).
I would assume you want hostname to just get the site name.

If you are insisting to use the window.location.origin
You can put this in top of your code before reading the origin
if (!window.location.origin) {
window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}
Solution
PS: For the record, it was actually the original question. It was already edited :)

Your primary question has been answered above. I just wanted to point out that the regex you're using has a bug. It will also succeed on foo-domain.com which is not a subdomain of domain.com
What you really want is this:
/(^|\.)domain\.com$/

MDN: https://developer.mozilla.org/en/DOM/window.location
It seems that you will get the same result for both, but hostname contains clear host name without brackets or port number.

Just to add a note that Google Chrome browser has origin attribute for the location. which gives you the entire domain from protocol to the port number as shown in the below screenshot.

Related

Make google Recaptcha work with special characters in the domain name

I was setting up an API key for a site with the swedish charachter ä in the domain name (http://sälja.io) but it did not initialize the recaptcha.
Then trying an api key for the equivalent url http://xn--slja-loa.io which worked when reaching the site from http://xn--slja-loa.io but not http://sälja.io.
Then I found the secure token which should work on all domains. It initialized the recaptchas on all domains and was also working on all tested domains, except the one with ä in it.
https://developers.google.com/recaptcha/docs/secure_token
Is there any way to get it working also with ä in the domain name ?
Edit
Since an api-key for http://xn--slja-loa.io is working from android when accessing the site from http://sälja.io, it might be how the browser interprets the domain. Eg. firefox interprets http://sälja.io as domain http://sälja.io and cannot get a response from google servers that will not allow ä in domain names. Android inteprets http://sälja.io as http://xn--slja-loa.io and will get a response since it's not containing ä. Any thoughts about this ? Is there any way to force the browser to interpret http://sälja.io as http://xn--slja-loa.io ?
Edit2
Code examples can be reached on sälja.io/test, 178.62.187.163/test and xn--slja-loa.io/test
Edit3
As of today (25.11.2015) it seems not to be possible to use recaptcha with a special charachter like ä in the domain name. Since aishwat singh have been helping the most to coming to this conclusion within the time for the bounty he will be rewarded, however an answer will be accepted when a solution can be provided for this problem.
I tried it just now and I am able to generate key for example-ä.se 6Ld8VRETAAAAALRXFNxmjEeVzbg2y5vdWv7THwJz
will post a complete working example shortly
EDIT 1
Here's git repo for code and same running on heroku
Ok it's not a complete fix because i used herokuapp.com as domain so example-ä.herokuapp.com becomes a sub domain and works
(however when earlier i tried it created a key for example-ä.se too but on loading page at captcha it gives invalid domain, figured out that was original issue, i thought you were not able to generate key for this domain)
Will try for a complete fix
EDIT 2
Btw you can specify your domain ip too, check this discussion
For me heroku free account doesn't provides ip of domain so it's difficult for me to test it
Also i was reading this thread
Figured out if i specify domains list as just com it accepts. In your case, just specify se as domains and it should work , google doesn't checks out exact url it just checks domain
Hope it helps, Will look into stoken approach too
you can read this post:
http://webdesign.tutsplus.com/tutorials/how-to-integrate-no-captcha-recaptcha-in-your-website--cms-23024
.....................

Parse host from url without subdomains etc

I'm working on a chrome-extension that reads the domain from window.location.hostname. Now for this extension to work properly, I need to be able to separate subdomains and other url variation to the same host. example:
I need all of the following url:s
www.google.com
accounts.google.com
photos.google.se
example.google.co.uk
https://google.com
all of these need to be resolved to, in this case, "google", in a way that is reliable and will work for any website with sometimes quirky subdomainconfigurations.
this is my current aproach, somewhat simplified:
var url = window.location.hostname.split(".") //returns an array of strings
for(i=0;i<url.length;i++){
if(url[i].match(domainregex) //regex for identifying domains ".com",".se",".co.uk" etc
return url[i-1] //usually what I'm after is directly before the domain, thus i-1
}
This approach is alot of hassle, and has proven unreliable at times...Is there any more straitforward way of doing this?
A more reliable solution to strip the top level domain part and get the main domain part is to use Public Suffix List which is used by Firefox and Chrome and other browsers.
Several js parsers of the list data are available if you don't want to write your own.
I had to do it for my fork of edit-my-cookies, so It will able to change profile of cookies per site. (https://github.com/AminaG/swap-my-cookies-multisite/blob/master/js/tools.js)
It is what I did, and it is working for me. I am sure if it not complete solution, but I am sure it can helps.
var remove_sub_domain=function(v){
var is_co=v.match(/\.co\./)
v=v.split('.')
v=v.slice(is_co ? -3: -2)
v=v.join('.')
console.log(v)
return v
}
it is working for:
www.google.com
accounts.google.com
photos.google.se
example.google.co.uk
google.com
if you want it to work also for:
http://gooogle.com
You first need to remove the protocol:
parser=document.createElement('a');
parser.href=url;
host=parser.host;
newurl=remove_sub_domain(host);

Replace domain in url for publishers academia login

When working outside of my university IP domain, I have to use a login server to access publishers websites.
Most url that were of the form http://pubs.domain.org/XXX.htmlare transformed into http://pubs.domain.org.gateway.university.edu/XXX.html
The problem is: most publishers websites have a useless search tool, so I use google and land on the regular website, and using Web of Knowledge outside of the university often fails to connect to the publisher. I have found that replacing manually the URL works as long as I have authentified in the last hour.
I am searching for a way of using a bookmarklet to do this automatically. I have found this question that seems to be what I'm looking for, but I never used javascript before and have been unable to adapt it.
Bookmarklet to edit current URL
Thanks!
try
javascript:(function() {
window.location.href =
location.protocol
+ '//'+location.hostname
+ '.gateway.university.edu'
+ location.pathname
+ location.search;
})();
I've encountered this exact situation myself recently. As you want to append a suffix to the hostname, but otherwise leave the URL intact, you can edit window.location.hostname directly to trigger a reload:
javascript:window.location.hostname += '.gateway.university.edu';
or with closure:
javascript:(function() {
window.location.hostname += '.gateway.university.edu';
})();
window.location.href = window.location.href.replace("://pubs.domain.org","://pubs.domain.org.gateway.university.edu");

Combine explicit protocol specification with relative URL

I have a page that is accessed via HTTP. This page links to another page on the same server using HTTPS. What is the most elegant way, using HTML and/or Javascript, to force a transition to HTTPS while using a relative URL?
Basically, I want the opposite of a protocol-relative URL. I want to explicitly specify HTTPS WITHOUT hardcoding the hostname into the URL.
I'm working on a large legacy site so a solution using unobtrusive javascript with minimal changes to existing markup is ideal.
I realize that enforcing HTTPS is better performed at the destination page, but that isn't an option in this case.
$("a").each(function () {
this.href = "https://" + window.location.host + this.pathname + this.search + this.hash;
});
You could provide a more specific selector to make sure it doesn't mess up any links you didn't intend to change, but I leave that up to you since you know the requirements.
I think you're going to have to build the URL yourself from the pieces on window.location.
var path = anchor.href;
var httpsUrl = "https://" +
window.location.host +
(path.charAt(0) === '/' ? path : window.location.pathname + '/' + path);
or something like that (esp. if there's are parameters etc).
edit — it's been noted that modern browsers will give back the complete URL when you access the "href" value, making this an even easier problem to solve in those cases (as you just have to fix the protocol prefix). (Thanks #Daniel!)

Can I use localhost as the domain when setting an HTTP cookie?

I am using a jQuery plugin to set cookies and when I use localhost for the domain it will not store the cookie.
Here is the plugin I am using with jQuery 1.2.6.
http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/
Below is the code that I am using. You can see it does not like localhost, and I am running it from a development web server on localhost. One detail is that I am running off port 4005 but that should not affect the domain, AFAIK.
$(function() {
console.log('Testing');
var one = $.cookie('Test.One');
var two = $.cookie('Test.Two');
var three = $.cookie('Test.Three');
console.log(['one', one]);
console.log(['two', two]);
console.log(['three', three]);
$('#div1').text(one);
$('#div2').text(two);
$('#div3').text(three);
$.cookie('Test.One', 'Test 1');
$.cookie('Test.Two', 'Test 2', { path: '/' });
$.cookie('Test.Three', 'Test 3', { path: '/', domain: 'localhost' });
});
I had similar problem with setting cookies. Make up a domain name and add it to your hosts file as 127.0.0.1. Then run web application on that domain.
I think the domain name of a cookie must have exactly two dots (not counting the final dot after the TLD). So .something.localhost is okay, .google.com is okay, but .localhost or google.com is not. But a glance at RFC 2965 suggests that it's more complicated than that... you might want to read that document, especially section 3.3 (and/or its precursor, RFC 2109).
I updated the jQuery plugin to not add the domain to the cookie when it is localhost. That solves my problem without touching the hosts file.
var domain = (options.domain && options.domain !== 'localhost') ? '; domain=' + (options.domain) : '';
I'm using Code Ignitor, and setting the domain to an empty string fixed my problem while working on the application on localhost. I believe this is the better solution as everyone in the development team then doesn't need to mess with their hosts files on Windows.
Production domain values can be put in the config.php of Code Ignitor when deployed on a live site.
I tried setting the host file to use an alternate name (local.acme.com) and I can now set cookies on that domain. It seems I cannot set cookies on localhost, at least not with Firefox. I do not recall that being a restriction for cookies. I would like to understand what is going on here.
Also, I did try just making the domain in the hosts file simply "dev" but that did not work. I had to use a name that ended in .com or another tld to make it work.
Simplest solution for me to resolve this was to use 127.0.0.1 instead of localhost ;-)
That works fine in Firefox!
Cookie needs to specify SameSite attribute, None value used to be the default, but recent browser versions made Lax the default value to have reasonably robust defense against some classes of cross-site request forgery (CSRF) attacks.
Along with Domain=localhost your cookie should look something like this
document.cookie = `${name}=${value}${expires}; Path=/; Domain=localhost; SameSite=Lax`;
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite

Categories