【问题标题】:call parent javascript function from iframe从 iframe 调用父 javascript 函数
【发布时间】:2013-10-28 05:15:16
【问题描述】:

在 node-webkit 中,从 iframe javascript 调用到父 javascript 对我不起作用。

结果我试图在默认浏览器的 iframe 中启动一个链接 我想在父窗口中调用一个函数以便调用:

gui.Shell.openExternal("link");

感谢任何帮助。提前致谢。

【问题讨论】:

  • 您要打开的网址是什么?
  • 我正在尝试打开一个链接到另一个在其他地方运行的服务器。如果我可以让 google.com 在默认浏览器中打开就足够了。

标签: node-webkit


【解决方案1】:

你要做的,就是截取内部框架中的链接。

这里有一个 iframe,所有链接都将在默认浏览器中打开,而不是在 Node WebKit 上下文中打开。我希望这会有所帮助。

试试这个:

<!DOCTYPE html>
<html>
 <head>

  <script type="text/javascript">
    window.gui = require('nw.gui');

    handleLinks = function(event)
    {
            var href;

            function checkLinks(element) 
            {
                if (element.nodeName.toLowerCase() === 'a') 
                {
                    href = element.getAttribute('href');
                    if (href)
                    {
                        gui.Shell.openExternal(href);
                        // important, prevent the default event from happening!
                        event.preventDefault();
                    }   
                }                   
                else if (element.parentElement) 
                {
                  checkLinks(element.parentElement);
                }
            }
            checkLinks(event.target);
    };

     function isLoaded() 
     {
       // let's see if the iframe has finished loading
       var iframe = document.getElementById('myframe');

       if (iframe && iframe.contentWindow && iframe.contentWindow.document &&
           iframe.contentWindow.document.body &&
           iframe.contentWindow.document.body.innerHTML) 
           {
            //now deal with links
            iframe.contentWindow.document.body.addEventListener('click', handleLinks, false);
           } 
           else 
           {
             // not yet, let's wait a bit and try again
             setTimeout(isLoaded, 300);
           }
     };
   </script>
 </head>
 <body>
   <iframe id="myframe" src="http://www.google.com" onLoad="isLoaded();" style="width: 100%;" seamless="true" nwdisable nwfaketop></iframe>
   <div>
    Links in the normal browser should still work in the Node Webkit environment.
   </div>
   <footer>
    <a href="http://www.yoursitehere.com">Whaddayaknow</a>
   </footer>
 </body>
</html>

【讨论】:

  • 高兴 - Node Webkit 是一个如此强大的工具!
  • 如果您在 iframe 中加载外部网站,这不起作用,对吧?你得到错误:SecurityError: Blocked a frame with origin "http://..." from accessing a frame with origin "http://...". Protocols, domains, and ports must match
  • 我实际上是用它来加载一个外部网站,但是在一个 Node Webkit 应用程序中。不过,我从来没有遇到过这个安全问题。您可以发布一个重现此问题的示例吗?
  • 我正在使用您的代码:iframe.contentWindow.document.body.addEventListener。这会产生错误。
  • 我使用的网站没有任何错误,使用完全相同的代码。
猜你喜欢
  • 2011-10-19
  • 2017-04-28
  • 2011-01-10
  • 2012-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-05
  • 1970-01-01
相关资源
最近更新 更多