0

I have an iFrame that is running some Javascript and I want the iFrame to behave differently depending on which page it is loaded into. I found this code which works brilliantly but it shows me the url of the iFrame not the parent.

 var Page1 = "page1.html";
 var Page2 = "page2.html";
 var thisUrl = decodeURI(window.location);
 var urlChunks = thisUrl.split("/");

for (var chunk in urlChunks) {
alert('chunk: ' + chunk);
alert('urlChunks[chunk]: ' + urlChunks[chunk]);

if (urlChunks[chunk] == Page1) {
alert('inside index.html');

}

else if (urlChunks[chunk] == Page2) {

}

else
{

}

}

What can I change the

decodeURI(window.location);

to in order to get it to read from the parent.

Jack
  • 2,625
  • 5
  • 33
  • 56
  • If you want the parent url, that is already answered here: http://stackoverflow.com/questions/115526/is-there-a-way-to-get-the-parent-url-from-an-iframes-content – eddy147 Nov 20 '11 at 13:00
  • that doesn't seem to work for me =S it returns undefined instead of the parent url. Could my file structure be affecting this. – Jack Nov 20 '11 at 13:04
  • @eddy147 sorry didn't tag your name – Jack Nov 20 '11 at 13:04

1 Answers1

1
window.parent.location

Remember that JavaScript has the Same-Origin restriction, so when the parent document is a different origin (eg. domain), you will most probably get an access-denied exception.

Rafael
  • 18,349
  • 5
  • 58
  • 67
  • The code doesn't seem to run =/. My parent is in Website/profile/Page1.html but my frame is in Website/frames/child.html could that cause an access-denied exception – Jack Nov 20 '11 at 13:00
  • No, it shouldn't trigger any exception in that case. I have too little information to tell you why my code doesn't work for you. It should. parent property is the right way to get parent of a framed document. – Rafael Nov 20 '11 at 13:05
  • Further, it's window.parent.location.url otherwise you may just be returning the location object. – Matthew Nov 20 '11 at 14:15
  • 1
    @Matt: not really. url is not a property of window.location. document has URL property. If you need the URL as string, then use parent.location.href, but if you use decodeURI on the location object, it will be converted to string. – Rafael Nov 20 '11 at 18:25
  • @Rafael My mistake. window.parent.location.href – Matthew Nov 20 '11 at 18:56