I have an application where an iframe loads a Blazor application that needs to use a function (invoked from Blazor) available only in the main page. I can add the parent function into the iframe's window successfully, but the Blazor library performs an instanceof Function
check, which for some reason is not true when loading a function to an iframe's contentWindow
this way, even though the function itself is executable.
Is there a way to construct this so instanceof Function
returns true? findJsFunction
is provided by Blazor and cannot be modified.
I've tried:
main
<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>
console.log(Function == document.querySelector('#myFrame').contentWindow.Function)
returns false, so that is likely the cause of your issue.
Using Object.setPrototypeOf
to set the prototype of the test
function in the iframe, to the Function
of the iframe, appears to work:
<iframe id="myFrame" srcdoc="<button onclick="console.log(window.test instanceof Function)">Click me</button>"></iframe>
<script>
function test() {
console.info('test');
}
document.querySelector('#myFrame').contentWindow.test = test;
Object.setPrototypeOf(document.querySelector('#myFrame').contentWindow.test,
document.querySelector('#myFrame').contentWindow.Function)
</script>
That throws security errors here in the snippet, but under https://jsfiddle.net/2j8oLgmt/ I am getting true
in the console, when clicking the button in the iframe. (You need to check the real browser console, not the one jsfiddle itself provides.)