在Javascript中抑制"权限被拒绝"错误

Mal*_*ala 9 javascript iframe permission-denied

我有一个JS函数,用于轮询iframe中的当前url,目的是确定iframe是否指向与主文档相同的站点.因此,代码基本上是:

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

从功能上讲,这段代码非常有效.但是,在错误控制台中,每次调用此函数并且iframe src不是本地时,我都会收到错误:

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

如何修复代码以避免这些错误?

谢谢,麻辣

Dan*_*man 12

将代码包装在try-catch块中应该能够捕获并处理这些错误.