使用 javascript 转义 iframe

Escape iframe with javascript

本文关键字:iframe 转义 javascript 使用      更新时间:2023-09-26

我知道如何转义iframe。我有一个链接:

<a id="aaa" href="http://localhost/projectManagement/users" target="_parent" >Sign up</a>

通过单击该链接,我将转义iframe。

问题是我想在单击按钮而不是链接时转义 iframe。

我知道如何通过单击按钮来执行JavaScript,因此我一直在努力使用javascriopt执行该链接

我尝试过的东西:

HTML:(它位于iframe内(

<button onClick="tempEvent();" style="width: 500px; height: 50px; margin-top: -15px; font-size: 20px;">
      <b>
          click me              
       </b>
</button>
<div style="height: 15px;">
</div>
<a id="aaa" href="http://localhost/projectManagement/users" target="_parent" >Sign up</a>

JavaScript

<script>
    function tempEvent()
    {
        clickLink(document.getElementById('aaa'));  // this technique does not work on firefox!
        fireEvent(document.getElementById("aaa"),'click'); // this technique does not work in firefox eather.
        document.getElementById("aaa").onclick(); 
    }
    function clickLink(link) {
        if (document.createEvent) {
            var event = document.createEvent("MouseEvents");
            event.initMouseEvent("click", true, true, window,
                0, 0, 0, 0, 0,
                false, false, false, false,
                0, null);
            link.dispatchEvent(event);
        }
        else if (link.fireEvent) {
           link.fireEvent("onclick");
        }
    }
    function fireEvent(obj,evt){    
        var fireOnThis = obj;
        if( document.createEvent ) {
          var evObj = document.createEvent('MouseEvents');
          evObj.initEvent( evt, true, false );
          fireOnThis.dispatchEvent(evObj);
        } else if( document.createEventObject ) {
          fireOnThis.fireEvent('on'+evt);
        }
    }

</script>

我知道我可以用链接替换按钮,但我只是不明白为什么我无法实现这一目标!

编辑

即使我将链接放在按钮内也不起作用!

父级中的 Javascript:

function redirectMe(url) {
    window.location = url;
}

子 iframe 中的 JavaScript:

function tempEvent() {
    parent.redirectMe('http://localhost/projectManagement/users');
}

你可以一起绕过<a>,整个clickLink/fireEvent并不是真正需要的。 如果您确实需要激活链接上的单击事件,请查看jQuery及其click()函数。

<input type="button" onclick="try { window.parent.location.href = "http://example.com"; } catch(e) { }" />

或者,如果您不知道 url,或者只是将 url 存储在元素上:

<input type="button" href="http://example.com" onclick="try { window.parent.location.href = this.href; } catch(e) { }" />

请记住,onclick 事件并不总是必须引用函数。它能够直接从处理程序运行JavaScript代码,尽管大多数人更喜欢函数。

注意:我添加了 try { } catch(e) { } 语句,因为可能存在跨域问题,其中尝试操作父窗口会导致抛出错误。