Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling A Javascript function from Silverlight

I'm attempting to call a javascript function (in our code) from a silverlight control. I'm attempting to call the function via:

HtmlPage.Window.Invoke("showPopup", new string[] { "http://www.example.com" });

and I get the error "Failed to Invoke: showPopup"

I can call HtmlPage.Window.Invoke("alert", new string[]{"test"}); without issue, but not my own function.

I can also open up the page in question in the IE developer tools and manually call showPopup("http://www.example.com") and it works as expected.

So the js function works, and the Silverlight binary can find other js functions. What am I missing here?

Additional Notes:

  • The function call is in a button click event handler, so it happens after the page (and the script) have been loaded)
like image 546
Ryan Avatar asked Feb 10 '09 21:02

Ryan


3 Answers

Aha! I figured it out. Our app uses an iframe, so the rendered html looks something like this

<html>
<head></head>
<body>
Stuff
<iframe>
    <html>
        <head></head>
        <body>Other Stuff</body>
    </html>
</iframe>
<body>
</html>

And the Silverlight control in question is in the iframe. The problem was that the file that contained the showPopup function was referenced in the outer <head> (why I could call the function with the IE toolbar) but not the inner <head>. Adding a reference to the file in the in-the-iframe <head> solved the problem.

Sort of anticlimactic, but thanks for all the help.

like image 102
Ryan Avatar answered Oct 05 '22 07:10

Ryan


Actually referencing the script again from the iframe is not the most efficient way to reference code contained in the parent. If your function is called "showPopup", you can insert this in your iframe:

<script type="text/javascript">
    var showPopup = parent.showPopup;
</script>

And voilà. The explanation for this is that all "global" functions and objects are part of this "global namespace"... which is the "window" object. So if you're trying to access "global" functions from a child, you need to either call the function on the parent (e.g parent.showPopup('....')) or declare a local alias for it (which is what we do in the above example).

Cheers!

like image 43
Oli Avatar answered Oct 05 '22 07:10

Oli


Is the showPopup javascript function on the same html or aspx page as the Silverlight control? You will normally get the "Failed to Invoke ..." error if the javascript function does not exist:

HtmlPage.Window.Invoke("functionThatDoesNotExist", new [] { "Testing" });

alt text

What browser are you using when you are getting this problem?

Are you using the latest version of Silverlight?

Are you using the ScriptableType attrbiute anywhere?

Is it possible to list the code for a short but complete program that causes this problem to happen on your machine...

like image 30
Peter McG Avatar answered Oct 05 '22 05:10

Peter McG