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:
- manually setting the prototype to Function
- using parent.test
- defining the function test also in the iframe and then overwriting it
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>
3
Answers
Interesting problem, I expect it is to do with context and that your creating a Function in the iframe with the prototype of the parent pages Function object.
I think to get around this you need to have the function created by the JS runtime context in the iframe.
The things I think you can try are injecting a script tag to load a JS file, or you could inject a script tag that contains your JS function.
That was the function will be created with the correct context and should be an instance of the iframe’s Function object.
returns false, so that is likely the cause of your issue.
Using
Object.setPrototypeOf
to set the prototype of thetest
function in the iframe, to theFunction
of the iframe, appears to work: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.)