call parent javascript function from iframe

梦想与她 提交于 2019-12-18 07:14:02

问题


In node-webkit, call from iframe javascript to parent javascript doesnt work for me.

I am trying to launch a link in the iframe on the default browser as a result I want to call a function in the parent window so as to call:

gui.Shell.openExternal("link");

Any help is appreciated. Thanks in advance.


回答1:


What you want to do, is to intercept links in the internal frame.

Here we have an iframe where all links will open in the default browser, not in the Node WebKit context. I hope this helps.

Try this:

<!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>


来源:https://stackoverflow.com/questions/19627591/call-parent-javascript-function-from-iframe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!