I use document.URL to detect if a user is on index.html:
if(document.URL.indexOf("index") >-1) return true;
But if the user types "mydomain.com" or "mydomain.com/" then the test returns false.
I could try:
if(document.URL ==="http://myDomain.com") return true;
But I want to use this code on different domains. Any suggestions?
There are so many permutations of URL that could mean that a user is on index.html. Instead could you not put a var within that file:
<script type="text/javascript">
on_index = true;
</script>
Just check if on_index is not undefined and is true. That'll be accurate 100% of the time.
javascript Location object has many useful properties, in particular, you can examine location.pathname.
Basically, you're on the "index" page if the pathname is 1) empty 2) is equal to a slash / 3) starts with index or /index.
var p = window.location.pathname;
if (p.length === 0 || p === "/" || p.match(/^\/?index/))
alert ("on the index page!")
See Javascript .pathname IE quirk? for the discussion of leading slash issues.
There isn't a direct link between files and URLs. Additionally, index.html does not need to be in the site's root and the default page does not need to be index.html.
If you want a generic solution, you're probably out of luck. If you want a solution for your particular case, you can just provide that info from the page itself, e.g. defining an ID or class name:
<body class="index">
... or a JavaScript variable:
// Pick one
var page = 'index';
var isIndex = true;
If all you want is some simple string manipulation with current location, grab the pathname property of the window.location object:
// Untested
if( window.location.pathname=="/" || window.location.pathname=="/index.html" ){
}
You could use
if (document.location.pathname === '/' ||
document.location.pathname.indexOf('index') >-1 ) {
return true;
}
If you have access to the actual page and not just the script then you should follow #Ben Everard's advice.
Just make sure you include the snippet he proposes before your script..
Related
I'm attempting to use javascript to determine if the user is using a certain language and if they're not using english then for the page to load a different page BUT with the params of which I've grabbed from the url.
I have been able to load the page with the params but I keep falling into a loop reloading the page, even after skimming through the countless other examples, such as: this or this.
function locateUserLanguage() {
var languageValue = (navigator.languages ? navigator.languages[0] : (navigator.language || navigator.userLanguage)).split('-');
var url = window.location.href.split('?');
var baseUrl = url[0];
var urlParams = url[1];
if (languageValue[0] === 'en') {
console.log('no redirect needed, stay here.');
} else {
// I tried to set location into a variable but also wasn't working.
// var newURL = window.location.href.replace(window.location.href, 'https://www.mysite.dog/?' + urlParams);
window.location.href = 'https://www.mysite.dog/?' + urlParams
}
} locateUserLanguage();
I've attempted to place a return true; as well as return false; but neither stop the loop.
I've tried window.location.replace(); and setting the window.location.href straight to what I need, but it's continuing to loop.
There is a possibility that the script in which this function is written is executed in both of your pages (english and non-english) on load. So, as soon as the page is loaded, locateUserLanguage function is executed in both english and non-english website causing the infinite loop.
You need to put a check before you call locateUserLanguage function.
Suppose english website has url = "www.myside.com" and non-english website has url "www.myside.aus". So the condition needs to be
if (window.location.host === "www.myside.com") { locateUserLanguage() }
This will make sure that locateUserLanguage is called only in english website.
Or other apporach can be to load this script only in english website which will avoid the usage of conditional statement.
Hope it helps. Revert for any doubts.
I am an absolute beginner in JS.
1) What I'm trying to do:
My web pages are composed of an index.php which is the same for all the files of a directory and one of a set of content.inc, like this: index.php?open=content.inc. This is done by a PHP snippet in the index.php and works well.
However, Google indexes all the content.inc files. The user's browser then displays the content.inc without the framing index.php. This I want to avoid. I therefore add a modest script at the beginning of each content.inc (which I would convert into a function once it runs) to tell the browser that instead of displaying the content.inc, it should display index.php?open=content.inc.
2) My unworkable solution:
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
if (filename.indexOf("index.php") = -1)
{ var frame_name = "index.php?open="+filename;
window.location.replace(frame_name);
};
The browser (Firefox 60) ignores this; it displays content.inc. (I also have versions of this script which get the browser into an endless loop.)
What is wrong here? Please help!
PS: Please be assured that I have done extensive web search on this problem and found many pages of complaints about location.replace getting into an infinite loop; but none matches my situation. However, I gratefully accept a helpful link as an answer.
For starters, you have an error in this line:
if (filename.indexOf("index.php") = -1)
That's an assignment and will always evaluate to true, you need to use == or === (which should be more performant).
The guilty line is on your test case (see JP de la Torre answer). And to improve, here's a snippet to demo how to analyze the url with a regular expression :
function redirect(url) {
if(url && url.indexOf('.inc') >= 0) {
return url.replace(/\/(\w+)\.inc/, '/index.php?open=$1');
}
return url;
}
let urls = [
window.location.href,
'http://google.fr',
'http://example.com/index.php?open=wazaa',
'http://example.com/wazza.inc'
];
urls.forEach(url => {
console.log(url, ' => ', redirect(url));
});
The regexp will capture any text between a / and .inc. You can use it then as replacement value with the $1.
And applied to your case, you simply need :
if(window.location.href.indexOf('.inc') >= 0) {
window.location.href = window.location.href.replace(/\/(\w+)\.inc/, '/index.php?open=$1');
}
You can also use .htaccess server side to redirect request for .inc files on your index.php if mod_rewrite is enabled.
The solution to the problem of including an INC file called separately is the one proposed by Bertrand in his second code snippet above. It presupposes (correctly) that the inc extension is omitted in the replacement.
As I reported above, Firefox may get into an endless loop if it opens a PHP file directly, i.e. without involving the local host (with its php module).
I am attempting to write a script that would launch a modal if the user enters a page from any external link. I am assuming the document.referrer is the way to do it, but not familiar enough with JS as to how to implement it in an "if" conditional. Any suggestions are appreciated.
I'm assuming it would look something like this?
if (document.referrer !== window.location.hostname) {
// do something
}
If you would like to check if the user entered a page from an external link, you can parse the document.referrer to get just the hostname, and compare that with window.location.hostname:
var parser = document.createElement('a');
parser.href = document.referrer;
var isExternallyReferred = document.referrer.length > 0 && parser.hostname !== window.location.hostname;
if (isExternallyReferred) {
// launch modal
}
I'm doing some old url redirection with javascript.
My old urls in Google index are something like domain.com/#!about/c3g8. My new url for about us page is like domain.com/#about since I have change my site to one paged site.
My old site has had 4 pages without including root page. Each page has had a unique ending. They are -
/c3g8
/cjg9
/cee5
/cce3
The redirections cannot be done in .htaccess because they contain hash(#) character in them. Therefore, I have no choice but javascript. My current redirect js code is as follow
if(document.URL.indexOf(/!|\/c3g8|\/cjg9|\/cee5|\/cce3/)) {
var url_new = document.URL.replace(/!|\/c3g8|\/cjg9|\/cee5|\/cce3/,'');
window.location = url_new;
break;
}
All inner pages redirect properly but home page became a redirect loop and until I press Esc key twice.
I have this $('a[href^=#]').bind("click", function(event){.... code in my js too. How can I redirect without leading to a redirect loop?
Thanks in advance!
You're mixing regex matching and indexOf. The if condition is always going to evaluate to -1 which is truthy, so the the redirect always happens.
Use regex.test() instead, and use the g modifier to tell it to replace all instances...
if(/!|\/c3g8|\/cjg9|\/cee5|\/cce3/.test(document.URL)) {
var url_new = document.URL.replace(/!|\/c3g8|\/cjg9|\/cee5|\/cce3/g,'');
window.location = url_new;
break;
}
Try this:
var url_new = document.URL.replace(/!|\/c3g8|\/cjg9|\/cee5|\/cce3/,'');
if(document.URL !== url_new){
window.location = url_new;
}
I am using an online store solution which allows me set up a simple online shop. I cannot use any code other than html/css/javascript.
I have put in a simple image-slider in the template. But i want this slider to only be shown on the frontpage. Now its shown on every-page.
Can i use a javascript functions that says something like this: "if url is "www.example.com" then show image-slider else hide it."
Something like this maybe?
<script>
$(function() {
if(document.URL == "http://example.com/") {
...
...
</script>
Thanks on beforehand :)
I don't know the exact circumstances of what you're trying to do it or why you'd need it, but
if (location.href == "http://example.com")
Should do it. Location.href returns the URL of the page, like "document.URL" in your example.
If you're looking to just get certain parts of the URL, this is a really cool tip I found here.
var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";
parser.hostname; // => "example.com"
parser.pathname; // => "/pathname/"
Essentially what this does is creates a link element in your JavaScript that has properties that return different parts of the URL. This would be relevant if there could be multiple URLs for your index page. For instance, if the user is currently at http://example.com/index#something.
(location.href == "http://example.com/")
Would return false. However, if you did this in your code,
var parser = document.createElement('a');
parser.href = "http://example.com/index#something";
(parser.hostname+parser.pathname == "example.com/index")
That last line would return true for both http://example.com/index and http://example.com/index#something.
Taking the information you've given about the website, here's my best guess as to what your code should look like.
var parser = document.createElement('a');
parser.href = location.href;
if (parser.hostname+parser.pathname != "example.com/index") //If user isn't on the index page
{
$(".slidewrap").hide(); //Hide the div with the class slidewrap
}
window.location is the right area, it exposes a hostname property so you can check just the site name rather than the whole URL, and pathname for just the local path within the site. See https://developer.mozilla.org/en-US/docs/Web/API/Location
So if the home page is http://www.example.com/, then window.locaton.pathname === '/'
i.e.
<script>
$(function() {
if (location.pathname == "/") {
...
}
});
</script>
Im just adding the solution as an answer as i got it to work by mixing j4g and duncans codes:
<script>
$(function() {
if(location.pathname !== "/") {
$("#slidewrap").hide();
}
});
</script>
As i understand it. It says: If location is not index then hide #slidewrap :D And that works perfectly. Thanks.