I have a link where I want to get the top level domain name of the domain clicked.
In my example I have
click on this link
When I click on it I want an alert saying
www.example.com
I know window.location.host does this for the actual location of the site but am not sure how to get this for the individual href
I have tried the below but it returns
jQuery(document).on("click", "a", function (event) {
event.preventDefault();
var id = jQuery(this).attr('href') || 'nohref';
alert(window.location.host);
alert(id);
});
http://www.example.com/this/that
rather than
www.example.com
What is the best way to achieve this?
It's pretty straightforward actually, no need for regular expression:
jQuery(document).on("click", "a[href]", function (event) {
event.preventDefault();
alert(this.hostname);
});
See MDN - HTMLAnchorElement.
I'm not sure if it works in Internet Explorer though.
Try
jQuery(document).on("click", "a", function (event) {
event.preventDefault();
var id = jQuery(this).attr('href') || 'nohref';
var domain = id.match(/http[s]?\:\/\/(.*?)[\/$]/)[1]
alert(domain);
});
var domain = jQuery(this).attr('href').match(/^https?:\/\/([^\/]+)/);
if (domain != null && typeof domain[1]!='undefined')
domain = domain[1];
else
domain = '';
You could take a stab at using document.domain, although it's not as widely supported as window.location.host.
Related
I am trying to trigger a button click on pageload with the piece of jQuery below
<script>
jQuery(function(){
jQuery('#clickson').click();
});
</script>
It works perfectly but I have this button id on every page, how can I use it such that it only triggers on homepage and subdomain homepages.
For example it should only fire on example.com, subdomain1.example.com, subdomain2.example.com and NOT on any other pages like example.com/path, subdomain1.example.com/path, subdomain2.example.com/path
Try checking location.href for selected url
jQuery(function() {
var loc = location.href;
// if `location.href` is equal to
// "example.com","subdomain1.example.com", "subdomain2.example.com"
// call `.click()` on `#clickson`
if (loc === "example.com"
|| loc === "subdomain1.example.com"
|| loc === "subdomain2.example.com") {
jQuery("#clickson").click();
}
});
jQuery(function() {
if (location.href === "http://stacksnippets.net/js") {
jQuery("#clickson")[0].click();
}
});
#home {
display:block;
position:relative;
top:400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<a id="clickson" href="#home">click</a>
<div id="home">home</div>
Since you said you were against hardcoded string approaches, heres a simple bit of code that will accept an array of pages. location.pathname is the section of the url coming after the domain and before the query string. to my knowledge, it is implemented in every browser i have ever encountered.
var pages=['/','/home'];
for(var i=0;i<pages.length;i++)
{
if(location.pathname==pages[i])
{
//do stuff you want here
break; //terminates the loop on first match
}
}
Use regex to match currect URL:
var href = window.location.href;
var regex = /(example\.com)$/i; // find only example.com at the end of URL
if ( regex.test(href) ){
// if passed
// do jQuery stuff here
}
I know this is a question much discussed but I can't figure out why it does not work for me.
This is my function:
function ShowComments(){
alert("fired");
var movieShareId = document.getElementById('movieId');
//alert("found div" + movieShareId.textContent || movieShareId.innerText);
//alert("redirect location: /comments.aspx?id=" + movieShareId.textContent || movieShareId.innerText + "/");
window.location.href = "/comments.aspx?id=" + movieShareId.textContent || movieShareId.innerText + "/";
var newLocation = window.location;
//alert("full location: " + window.location);
}
If I have the alerts uncommented or if I have Mozilla's bugzilla open it works fine, otherwise it does not redirect to the other page.
Any ideas why?
If you are calling this function through a submit button. This may be the reason why the browser does not redirect. It will run the code in the function and then submit the page instead of redirect. In this case change the type tag of your button.
From this answer,
window.location.href not working
you just need to add
return false;
at the bottom of your function
Some parenthesis are missing.
Change
window.location.href = "/comments.aspx?id=" + movieShareId.textContent || movieShareId.innerText + "/";
to
window.location = "/comments.aspx?id=" + (movieShareId.textContent || movieShareId.innerText) + "/";
No priority is given to the || compared to the +.
Remove also everything after the window.location assignation : this code isn't supposed to be executed as the page changes.
Note: you don't need to set location.href. It's enough to just set location.
Solution from here:
http://www.codeproject.com/Questions/727493/JavaScript-document-location-href-not-working
document.location.href = 'Your url',true;
Make sure you're not sending a '#' at the end of your URL. In my case, that was preventing window.location.href from working.
You can't use window.location.replace or document.location.href or any of your favourite vanilla javascript methods to redirect a page to itself.
So if you're dynamically adding in the redirect path from the back end, or pulling it from a data tag, make sure you do check at some stage for redirects to the current page. It could be as simple as:
if(window.location.href == linkout)
{
location.reload();
}
else
{
window.location.href = linkout;
}
I'll give you one nice function for this problem:
function url_redirect(url){
var X = setTimeout(function(){
window.location.replace(url);
return true;
},300);
if( window.location = url ){
clearTimeout(X);
return true;
} else {
if( window.location.href = url ){
clearTimeout(X);
return true;
}else{
clearTimeout(X);
window.location.replace(url);
return true;
}
}
return false;
};
This is universal working solution for the window.location problem. Some browsers go into problem with window.location.href and also sometimes can happen that window.location fail. That's why we also use window.location.replace() for any case and timeout for the "last try".
window.location.replace is the best way to emulate a redirect:
function ShowComments(){
var movieShareId = document.getElementById('movieId');
window.location.replace("/comments.aspx?id=" + (movieShareId.textContent || movieShareId.innerText) + "/");
}
More information about why window.location.replace is the best javascript redirect can be found right here.
In my case it is working as expected for all browsers after setting time interval.
setTimeout(function(){document.location.href = "myNextPage.html;"},100);
window.location.href wasn't working in Android.
I cleared cache in Android Chrome and it works fine.
Suggest trying this first before getting involved in various coding.
Go to your api route, make sure you are not missing a response such as
res.status(200).json(data);
I'm trying to A/B test our product drop view. below is the javascript code I'm using:
var url = window.location.href,
defaultType = 'Gallery',
otherType = 'List';
if(Cookie.read('SEARCHVIEW') == otherType && Cookie.read('viewTypeChanged') != otherType){
if(url.contains('v='+otherType)){
url = url.replace('v='+otherType, 'v='+defaultType);
}else if(url.contains('?')){
url = url + '&v='+defaultType;
}else{
url = url + '?v='+defaultType;
}
window.location = url;
}
After the page redirects in IE I get the dreaded 'null' is null or not an object and Object does not support this property or method errors.
This is happening in both IE 7 & 8
How can I fix this?
I was able to resolve the problem. and for future reference I'll post some code and explain.
The offending code looks like this:
<script type="text/javascript">
window.addEvent('domready', function(){
$('v_toggle').addEvents({
'mouseenter': function(e){
$('vertical_slide_container').show();
},
'mouseleave': function(e){
$('vertical_slide_container').hide();
}
});
});
</script>
</head>
<body>
<div class="mboxDefault">/div>
<script type="text/javascript">mboxCreate('header',etc...);</script>
My company uses Omniture for our A/B testing and my code was being run in the mboxCreate() function. You'll notice above that there is code adding a domready event which adds hover events to our navigtaion(which is incidentally below my mboxCreate() code). What was happening was my code was redirecting, which stopped the page from loading, which also signaled that the DOM was ready. So when I called the redirect, the DOM ready code was run and was trying to add hover events on DOM elements that did not exists.
Thus the 'null' is null or not an object' and the object does not support this method or property errors.
The solution to the problem was to remove all domready events before I redirected so my error free code looks like this:
var url = window.location.href,
defaultType = 'Gallery',
otherType = 'List';
if(Cookie.read('SEARCHVIEW') == otherType && Cookie.read('viewTypeChanged') != otherType){
if(url.contains('v='+otherType)){
url = url.replace('v='+otherType, 'v='+defaultType);
}else if(url.contains('?')){
url = url + '&v='+defaultType;
}else{
url = url + '?v='+defaultType;
}
window.removeEvents('domready');
window.location = url;
}
href is not a property of window it can be used with anchor() object, try to use only window.location and this should work.
How do I test to see if links are external or internal? Please note:
I cannot hard code the local domain.
I cannot test for "http". I could just as easily be linking to my own site with an http absolute link.
I want to use jQuery / javascript, not css.
I suspect the answer lies somewhere in location.href, but the solution evades me.
Thanks!
I know this post is old but it still shows at the top of results so I wanted to offer another approach. I see all the regex checks on an anchor element, but why not just use window.location.host and check against the element's host property?
function link_is_external(link_element) {
return (link_element.host !== window.location.host);
}
With jQuery:
$('a').each(function() {
if (link_is_external(this)) {
// External
}
});
and with plain javascript:
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
if (link_is_external(links[i])) {
// External
}
}
var comp = new RegExp(location.host);
$('a').each(function(){
if(comp.test($(this).attr('href'))){
// a link that contains the current host
$(this).addClass('local');
}
else{
// a link that does not contain the current host
$(this).addClass('external');
}
});
Note: this is just a quick & dirty example. It would match all href="#anchor" links
as external too. It might be improved by doing some extra RegExp checking.
Update 2016-11-17
This question still got a lot of traffic and I was told by a ton of people that this accepted solution will fail on several occasions. As I stated, this was a very quick and dirty answer to show the principal way how to solve this problem. A more sophisticated solution is to use the properties which are accessible on a <a> (anchor) element. Like #Daved already pointed out in this answer, the key is to compare the hostname with the current window.location.hostname. I would prefer to compare the hostname properties, because they never include the port which is included to the host property if it differs from 80.
So here we go:
$( 'a' ).each(function() {
if( location.hostname === this.hostname || !this.hostname.length ) {
$(this).addClass('local');
} else {
$(this).addClass('external');
}
});
State of the art:
Array.from( document.querySelectorAll( 'a' ) ).forEach( a => {
a.classList.add( location.hostname === a.hostname || !a.hostname.length ? 'local' : 'external' );
});
And the no-jQuery way
var nodes = document.getElementsByTagName("a"), i = nodes.length;
var regExp = new RegExp("//" + location.host + "($|/)");
while(i--){
var href = nodes[i].href;
var isLocal = (href.substring(0,4) === "http") ? regExp.test(href) : true;
alert(href + " is " + (isLocal ? "local" : "not local"));
}
All hrefs not beginning with http (http://, https://) are automatically treated as local
var external = RegExp('^((f|ht)tps?:)?//(?!' + location.host + ')');
Usage:
external.test('some url'); // => true or false
Here's a jQuery selector for only external links:
$('a[href^="(http:|https:)?//"])')
A jQuery selector only for internal links (not including hash links within the same page) needs to be a bit more complicated:
$('a:not([href^="(http:|https:)?//"],[href^="#"],[href^="mailto:"])')
Additional filters can be placed inside the :not() condition and separated by additional commas as needed.
http://jsfiddle.net/mblase75/Pavg2/
Alternatively, we can filter internal links using the vanilla JavaScript href property, which is always an absolute URL:
$('a').filter( function(i,el) {
return el.href.indexOf(location.protocol+'//'+location.hostname)===0;
})
http://jsfiddle.net/mblase75/7z6EV/
You forgot one, what if you use a relative path.
forexample: /test
hostname = new RegExp(location.host);
// Act on each link
$('a').each(function(){
// Store current link's url
var url = $(this).attr("href");
// Test if current host (domain) is in it
if(hostname.test(url)){
// If it's local...
$(this).addClass('local');
}
else if(url.slice(0, 1) == "/"){
$(this).addClass('local');
}
else if(url.slice(0, 1) == "#"){
// It's an anchor link
$(this).addClass('anchor');
}
else {
// a link that does not contain the current host
$(this).addClass('external');
}
});
There are also the issue of file downloads .zip (local en external) which could use the classes "local download" or "external download". But didn't found a solution for it yet.
const isExternalLink = (url) => {
const tmp = document.createElement('a');
tmp.href = url;
return tmp.host !== window.location.host;
};
// output: true
console.log(isExternalLink('https://foobar.com'));
console.log(isExternalLink('//foobar.com'));
// output: false
console.log(isExternalLink('https://www.stackoverflow.com'));
console.log(isExternalLink('//www.stackoverflow.com'));
console.log(isExternalLink('/foobar'));
console.log(isExternalLink('#foobar'));
The benefit of using this approach is that:
It would automatically resolve the hostname for relative paths and fragments;
It works with protocol-relative URLs
To demonstrate this, let's look at the following examples:
const lnk = document.createElement('a');
lnk.href = '/foobar';
console.log(lnk.host); // output: 'www.stackoverflow.com'
const lnk = document.createElement('a');
lnk.href = '#foobar';
console.log(lnk.host); // output: 'www.stackoverflow.com'
const lnk = document.createElement('a');
lnk.href = '//www.stackoverflow.com';
console.log(lnk.host); // output: 'www.stackoverflow.com'
With jQuery
jQuery('a').each(function() {
if (this.host !== window.location.host) {
console.log(jQuery(this).attr('href'));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can use is-url-external module.
var isExternal = require('is-url-external');
isExternal('http://stackoverflow.com/questions/2910946'); // true | false
/**
* All DOM url
* [links description]
* #type {[type]}
*/
var links = document.querySelectorAll('a');
/**
* Home Page Url
* [HomeUrl description]
* #type {[type]}
*/
var HomeUrl = 'https://stackoverflow.com/'; // Current Page url by-> window.location.href
links.forEach(function(link) {
link.addEventListener('click', function(e) {
e.preventDefault();
// Make lowercase of urls
var url = link.href.toLowerCase();
var isExternalLink = !url.includes(HomeUrl);
// Check if external or internal
if (isExternalLink) {
if (confirm('it\'s an external link. Are you sure to go?')) {
window.location = link.href;
}
} else {
window.location = link.href;
}
})
})
Internal Link
External Link
This should work for any kind of link on every browser except IE.
// check if link points outside of app - not working in IE
try {
const href = $linkElement.attr('href'),
link = new URL(href, window.location);
if (window.location.host === link.host) {
// same app
} else {
// points outside
}
} catch (e) { // in case IE happens}
Yes, I believe you can retrieve the current domain name with location.href. Another possibility is to create a link element, set the src to / and then retrieving the canonical URL (this will retrieve the base URL if you use one, and not necessarily the domain name).
Also see this post: Get the full URI from the href property of a link
For those interested, I did a ternary version of the if block with a check to see what classes the element has and what class gets attached.
$(document).ready(function () {
$("a").click(function (e) {
var hostname = new RegExp(location.host);
var url = $(this).attr("href");
hostname.test(url) ?
$(this).addClass('local') :
url.slice(0, 1) == "/" && url.slice(-1) == "/" ?
$(this).addClass('localpage') :
url.slice(0, 1) == "#" ?
$(this).addClass('anchor') :
$(this).addClass('external');
var classes = $(this).attr("class");
console.log("Link classes: " + classes);
$(this).hasClass("external") ? googleAnalytics(url) :
$(this).hasClass("anchor") ? console.log("Handle anchor") : console.log("Handle local");
});
});
The google analytics bit can be ignored but this is where you'd probably like to do something with the url now that you know what type of link it is. Just add code inside the ternary block.
If you only want to check 1 type of link then replace the ternaries with an if statement instead.
Edited to add in an issue I came across. Some of my hrefs were "/Courses/" like so. I did a check for a localpage which checks if there is a slash at the start and end of the href. Although just checking for a '/' at the start is probably sufficient.
I use this function for jQuery:
$.fn.isExternal = function() {
var host = window.location.host;
var link = $('<a>', {
href: this.attr('href')
})[0].hostname;
return (link !== host);
};
Usage is: $('a').isExternal();
Example: https://codepen.io/allurewebsolutions/pen/ygJPgV
This doesn't exactly meet the "cannot hardcode my domain" prerequisite of the question, but I found this post searching for a similar solution, and in my case I could hard code my url. My concern was alerting users that they are leaving the site, but not if they are staying on site, including subdomains (example: blog.mysite.com, which would fail in most of these other answers). So here is my solution, which takes some bits from the top voted answers above:
Array.from( document.querySelectorAll( 'a' ) ).forEach( a => {
a.classList.add( a.hostname.includes("mywebsite.com") ? 'local' : 'external' );
});
$("a").on("click", function(event) {
if ($(this).hasClass('local')) {
return;
} else if ($(this).hasClass('external')) {
if (!confirm("You are about leave the <My Website> website.")) {
event.preventDefault();
}
}
});
this works for me:
function strip_scheme( url ) {
return url.replace(/^(?:(?:f|ht)tp(?:s)?\:)?\/\/(www\.)?/g, '');
}
function is_link_external( elem ) {
let domain = strip_scheme( elem.attr('href') );
let host = strip_scheme( window.location.host );
return ! domain.indexOf(host) == 0;
}
I wish to have a link which opens popup when clicked however I wish it to open a page in a new window if the user doesn't have JS enabled.
The following doesn't seem to work,
<a id="tac-link" target="_blank" href="tac.html">terms and conditions</a>
function popUp(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=550,height=600,left = 445,top = 150');");
}
$('tac-link').click(function() {
popUp('tac.html');
return false;
});
I think you just have the id selector wrong. Try changing $('tac-link') to $('#tac-link').
Another approach:
$('a[target="_blank"]').click(function(e) {
window.open( this.href );
e.preventDefault();
});
In order to make this functionality more browser-compatible, you need to pass the event object to the click handler, then call e.preventDefault();.
example:
$( '#button' ).click( function( e ) {
//... your code...
e.preventDefault();
return false;
} );
Also note that event.preventDefault is not present in all browsers and will cause an error in things like IE7 (if memory serves.) To avoid that, use a general if-statement:
if (e.preventDefault) {
e.preventDefault();
}
e.returnValue = false;
This will prevent the error from being thrown. I believe jQuery uses this approach as well.
You simply missed the # indicating it's an id and not a node name.
$('#tac-link')
PS - I wouldn't recommend using eval, why not just store all the page variables in an object?
var pages = {};
function popUp( url ) {
var id = +new Date;
pages[id] = window.open( url );
}