9

I have a JS function that polls for the current url in an iframe, the purpose being to ascertain whether or not the iframe is pointing to the same site as the main document. As such, the code is basically:

function urlCheck()
{
  var location = document.getElementById('frameid').contentWindow.location.href;
  if (location)
  {
    // iframe src is currently local
  }
  else
  {
    // iframe src is currently not local
  }
}

Functionally, this code works perfectly. However, in the error console, every time this function is called and the iframe src is not local I get an error:

Permission denied for [site1] to get property Location.href from [site 2]

How can I fix my code to avoid these errors?

Thanks, Mala

Mala
  • 14,178
  • 25
  • 88
  • 119

2 Answers2

12

Wrapping your code in a try-catch block should be able to catch and deal with these errors.

DanSingerman
  • 36,066
  • 13
  • 81
  • 92
  • Thank you. I had no idea JS supported the try-catch methodology. The link was very helpful and my function now works error free :) – Mala Aug 18 '09 at 07:18
0

Actually, the error message is the info you want: As soon as the URL of the iframe points to a different domain, you get permission errors. This is a safety measure to avoid XSS attacks.

[EDIT] This means you can replace the code above with:

function urlCheck()
{
  try
  {
    document.getElementById('frameid').contentWindow.location.href;

    // iframe src is currently local
  }
  catch (e)
  {
    // iframe src is currently not local
  }
}
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • 2
    Can catching the error actually expose you to an XSS attack though? He's not actually changing permissions, just sanitizing what the user sees. – DanSingerman Aug 18 '09 at 07:23
  • 1
    Aaron: thank you for making sure I'm being careful. Actually, I don't really need the error message. Basically my code now says "set var location = false; try to set location to url of iframe; if (location) {do stuff}". As such, I'm pretty sure I'm safe. DanSingerman is correct - I just hate it when sites bog down my error console with errors (makes debugging my JS while surfing other sites a pain in the R-se =P) so I'm trying to avoid doing that to other people. – Mala Aug 18 '09 at 07:41