在父级 iframe 中创建函数,使其具有函数原型

问题描述 投票:0回答:1

我有一个应用程序,其中 iframe 加载 Blazor 应用程序,该应用程序需要使用仅在主页中可用的函数(从 Blazor 调用)。我可以成功地将父函数添加到 iframe 的窗口中,但 Blazor 库会执行

instanceof Function
检查,由于某种原因,以这种方式将函数加载到 iframe 的
contentWindow
时,即使该函数本身是可执行的,该检查也是不正确的.

有没有办法构造这个,以便

instanceof Function
返回 true?我试过了:

  • 手动将原型设置为 Function
  • 使用parent.test
  • 也在 iframe 中定义功能测试,然后覆盖它

主要

<iframe id="myFrame" src="url"></iframe>
<script>
    function test() {
        console.info('test');
    }
    document.querySelector('#myFrame').contentWindow.test = test;
</script>

iframe

<!-- blazor library does something like this -->
<script>
    function findJsFunction(name) {
        // the below is what fails because window[name] is never instanceof Function right now
        // is there a way I can get this to return true?
        if (window[name] instanceof Function) {
            window[name]();
        }
    }
</script>
<button onclick="findJsFunction('test')">Click me</button>
javascript html iframe
1个回答
0
投票
<iframe id="myFrame" src="url"></iframe>
<script>
    const myObject = {
        test() {
            console.info('test');
        }
    };
    window.myObject = myObject;
    document.querySelector('#myFrame').contentWindow.myObject = myObject;
</script>
<script>
    function findJsFunction(name) {
        if (typeof window[name] === 'object' && typeof window[name].test === 'function') {
            window[name].test();
        }
    }
</script>
<button onclick="findJsFunction('myObject')">Click me</button>
© www.soinside.com 2019 - 2024. All rights reserved.