views:

685

answers:

2

I have a Javascript that changes the host in links to match the current development/test server.

Here's an example:

var ndomain = document.domain;
var mydomain = 'www.foo.com';
var alink = document.getElementsByTagName('a');
for (var i = 0; i < alink.length; i++) {
    if (alink[i].href.length > 0){
     if (alink[i].host.substr(0, mydomain.length) == mydomain){
      alink[i].host = ndomain;
     }
    }
}

This changes references to http://www.foo.com/page.html to http://level1.test.foo.com/page.html.

This works in every browser I've tested except Safari (Mac or Win). I've searched and searched for information as to why and the closest reason I've come up with is the "same-origin policy".

Based upon my understanding of the same-origin policy, this should work because everything is under the foo.com domain. Could Safari be more strict in the fact that I'm going to a two level subdomain (e.g.level1.test)?

Can someone advise as to why this process doesn't work in Safari or how I can get it to work in Safari?

TIA!

A: 

You've got a syntax error on line 5 (3 opening brackets, only 2 closing brackets).

J-P
A: 

This shouldn't have anything to do with the same origin policy.

The same can be seen in Google Chrome. Both use the WebKit, so perhaps the WebKit DOM interface is the key to the problem.

Running the JS in the question in Chrome doesn't change hosts in links. Neither the JS debugger nor JS console report any issues.

Attempts to change the anchor.host property causes:

  • no error to be reported
  • no change in the anchor.host property

This suggests the anchor.host property is, for some reason, read-only.

The anchor.href property appears writeable, so this is probably your best option. The following code will work:

var ndomain = document.domain;
var mydomain = 'www.foo.com';
var alink = document.getElementsByTagName('a');
for (var i = 0; i < alink.length; i++) {
    if (alink[i].href.length > 0){
        if (alink[i].host.substr(0, mydomain.length) == mydomain){
            var currentHref = alink[i].getAttribute('href');
            var newHref = '';

            // Generate newHref based on currentHref and setting host as required

            alink[i].setAttribute('href', newHref);
        }
    }
}
Jon Cram