The code below only shows <span>
on / but wont show <span>
on .html so how can I get it to work on all pages with the specified domain? Please help.
<script type="text/javascript">
var myurl = "/";
var currenturl = window.location
if(myurl != currenturl) {
$("<span style=font-size:200px;>big</span>").replaceAll("body"); // check replaceWith() examples
}
</script>
The code below only shows <span>
on http://example./ but wont show <span>
on http://example./files/target.html so how can I get it to work on all pages with the specified domain? Please help.
<script type="text/javascript">
var myurl = "http://example./";
var currenturl = window.location
if(myurl != currenturl) {
$("<span style=font-size:200px;>big</span>").replaceAll("body"); // check replaceWith() examples
}
</script>
Share
Improve this question
edited Jan 8, 2021 at 15:32
Brian Tompsett - 汤莱恩
5,89372 gold badges61 silver badges133 bronze badges
asked Oct 2, 2011 at 22:25
user975763user975763
351 gold badge3 silver badges8 bronze badges
2 Answers
Reset to default 3This should work:
<script type="text/javascript">
var myurl = "www.myurl.";
var currenturl = window.location.hostname;
if(myurl != currenturl) {
$("<span style=font-size:200px;>big</span>").replaceAll("body"); // check replaceWith() examples
}
</script>
Per MDN Docs: https://developer.mozilla/en/window.location
What you wrote doesn't work because window.location returns a Location object, which is a host object. The variable myurl is a string. When paring a string and an object using the equals operator, the string is pared with the result of calling the object's toString method.
Host objects don't necessarily have a toString method, so attempting to call it could throw an error. Even if the location object of the browser has a toString method, it could return a string that is the value of any one of those properties, or something else.
As it happens, in most browsers window.location.toString() will return the current URL (which is specified in Moziall's Gecko DOM Reference). However, myurl contains the string http://myurl./ and the URL usually contains more information, such as the current page being displayed.
To match myurl, you need the protocol (http:) separator (//), hostname (myurl.) and a trailing "/" character, so:
var loc = window.location;
myurl = loc.protocol + '//' + loc.hostname + '/';
Or you could format myurl to match one of the properties of the location object to make the parison simpler.
PS. HTML5 is the first attempt at standardising the window object across browsers, so expect it to be a little different in different browsers—program defensively and test widely.