如何使用JavaScript单击iframe中的按钮

How to click a button inside iframe using JavaScript

本文关键字:按钮 iframe 单击 何使用 JavaScript      更新时间:2023-09-26

我试图在iframe内加载网页时触发点击事件,但它似乎不工作。

$(function(){
    $('#iframe').load(function(){
        var iframe = $('#iframe').contents();
        iframe.find("#btnSubmit").click(function(){
               alert("test");
        });
});
});

当我试图使用这个代码时,我得到了错误。

Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "null" from accessing a frame with origin "https://pptform.state.gov".  The frame requesting access has a protocol of "file", the frame being accessed has a protocol of "https". Protocols must match.

请告诉我如何解决这个问题。提前感谢

如果iframe的域和您的父站点不匹配,您就不能这样做,在这种情况下它们似乎不匹配。允许这样做会有很大的安全风险。

如果两个站点都在您的控制之下,您可以使用postMessage或使用一些URL哈希技巧跨iframe边界进行通信。然而,如果它们不在你的控制之下,你就无能为力了。