我有一个应用程序,其中 iframe 加载 Blazor 应用程序,该应用程序需要使用仅在主页中可用的函数(从 Blazor 调用)。我可以成功地将父函数添加到 iframe 的窗口中,但 Blazor 库会执行
instanceof Function
检查,由于某种原因,以这种方式将函数加载到 iframe 的 contentWindow
时,即使该函数本身是可执行的,该检查也是不正确的.
有没有办法构造这个,以便
instanceof Function
返回 true?我试过了:
主要
<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>
<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>