The code below only shows <span>
on http://example.com/ but wont show <span>
on http://example.com/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.com/"; var currenturl = window.location if(myurl != currenturl) { $("<span style=font-size:200px;>big</span>").replaceAll("body"); // check replaceWith() examples } </script>
Advertisement
Answer
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 comparing a string and an object using the equals operator, the string is compared 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.com/ 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.com) 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 comparison 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.