Javascript 如何在chrome浏览器中调用父窗口功能?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2550858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:51:24  来源:igfitidea点击:

How to call parent window function in chrome browser?

javascriptjqueryiframegoogle-chrome

提问by Pier Luigi

HI, I've surprisingly found problems, in Chrome browser, in calling window parent javascript functions. If I have a window with a javascript function defined in it

嗨,我惊讶地发现在 Chrome 浏览器中调用窗口父 JavaScript 函数时出现问题。如果我有一个定义了 javascript 函数的窗口

<script type="text/javascript">
  function dolink() {
   . . .
  }
</script>

and I have an iframeinside that window that makes this call using jquery

我在那个窗口中有一个iframe使用 jquery 进行这个调用

<script type="text/javascript">
 $(function() {
      $('a.arglink').click(function() {
         window.parent.dolink($(this).attr('href'));
         return false;
      });
 });
</script>

the call to dolinkfunction doesn't work. Stepping with chrome javascript debugger, it appears that window.parent.dolink is undefined. It's by design or a mistake that I made? In Firefox and IE it works fine.

dolink函数的调用不起作用。使用 chrome javascript 调试器,看起来 window.parent.dolink 是undefined。这是设计使然还是我犯的错误?在 Firefox 和 IE 中它工作正常。

回答by Pier Luigi

Finally found it!

终于找到了!

It seems that Chrome browser doesn't permit to reference a parent window accessing pages with the file:protocol. In fact I tested above code with files on my machine, so with a url like file:///C:/mytests/mypage.html. If I put that page in a Web Server, it all works as expected.

Chrome 浏览器似乎不允许引用使用file:协议访问页面的父窗口。事实上,我在我的机器上用文件测试了上面的代码,所以使用像file:///C:/mytests/mypage.html. 如果我将该页面放在 Web 服务器中,它会按预期工作。

回答by azeem

you should call code like that

你应该这样调用代码

if(function != undefined)
{
 $(function() {
      $('a.arglink').click(function() {
         window.parent.dolink($(this).attr('href'));
         return false;
      });
 });
}

回答by Alsciende

What about using frameElementand ownerDocument

如何使用frameElementownerDocument

<script type="text/javascript">
 $(function() {
      $('a.arglink').click(function() {
         window.frameElement.ownerDocument.parentWindow.dolink($(this).attr('href'));
         return false;
      });
 });
</script>

回答by Selim ?zbudak

I just simply did this and it works for me

我只是简单地做了这个,它对我有用

in iframe

在 iframe 中

function sendToParent() {
    parent.doSomething(); 
}
sendToParent();

in parent

在父母

function doSomething() {
    alert('did it!')
}