1

我如何在父窗口中调用 iframe 函数,我做了类似下面的操作,但似乎在 Firefox 中不起作用。相同的代码在 chrome 中完美运行。

window.frames["original_preview_iframe"].window.exportAndView(img_id);
4

4 回答 4

3

我认为你必须使用

document.getElementById('target_Frame').contentWindow.callingtargetFunction();

否则使用此网址描述您的问题的解决方案

从父页面调用 iframe 中的 JavaScript 代码

于 2013-05-02T11:32:03.123 回答
1

在“选择” iframe 后尽量不要键入 window:

window.frames["original_preview_iframe"].exportAndView(img_id);
于 2013-05-02T11:29:57.297 回答
1

会建议这个https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

对我有用的清晰 wiki 示例:

var o = document.getElementsByTagName('iframe')[0];
o.contentWindow.postMessage('Hello B', 'http://example.com/');

然后在 iframe 中:

function receiver(event) {
    if (event.origin == 'http://example.net') {
        if (event.data == 'Hello B') {
            event.source.postMessage('Hello A, how are you?', event.origin);
        }
        else {
            alert(event.data);
        }
    }
}
window.addEventListener('message', receiver, false);

https://en.wikipedia.org/wiki/Web_Messaging。)

于 2015-09-30T09:56:24.230 回答
0

有几种方法可以调用 iframe 函数。
我们假设您的 iframe id 是original_preview_iframe

方式一

你可以document.getElementById("original_preview_iframe").contentWindow.exportAndView()用来触发。

方式二

使用window.frames.
window.frames是一个数组,你可以window.name="this is iframe test"在“test.html”中设置iframe名称
然后你可以迭代数组,比较名称,然后触发它。

for (let i = 0; i < window.frames.length; i++) {
    if (window.frames[i].name === "this is iframe test") {
        window.frames[i].exportAndView()
    }
}

方式3

使用 postMessage。
在way1 和way2 中,需要在window对象中分配功能。

<body>
<script>
// this one
window.exportAndView = function(){}
// or this one
function exportAndView(){}
</script>
</body>

在 Way3 中,您可以隐藏 exportAndView 然后您也可以触发它。
这是一个例子。

// a.html
<html>
<body>
        <iframe id="original_preview_iframe" src="/b.html">
        </iframe>
        <script>
            // let postMessage trigger after b.html load
            setTimeout(function(){
                document.getElementById("original_preview_iframe").contentWindow.postMessage({data: "hi"});
            }, 500)
        </script>
</body>
</html>

// b.html (iframe html)
<html>
<body>
    <script>
        (function() {
            function exportAndView() {
                console.log("test");
            }
            window.addEventListener("message", (event) => {
                exportAndView()
            })
        })()
    </script>
</body>
</html>

然后在a.html中,可以尝试使用way1或者way2,比如document.getElementById("original_preview_iframe").contentWindow.exportAndView().
exportAndView不会被调用,因为范围问题。

于 2020-11-10T04:55:08.140 回答