Skip to content Skip to sidebar Skip to footer

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[] { '

Solution 1:

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.

Solution 2:

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:

<scripttype="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!

Solution 3:

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...

Solution 4:

Make sure your script is fully loaded before trying to invoke functions from it.

Solution 5:

Here's how I do it. But I'm creating silverlight without visual studio. I just have raw html, xaml, and js (javascript). Notice MouseLeftButtonUp and it's value "LandOnSpace"

<Canvasx:Name="btnLandOnSpace"Background="LightGreen"MouseLeftButtonUp="LandOnSpace"Cursor="Hand"Canvas.Top ="0"Width="70"Height="50"><TextBlockText="LandOnSpace"  /></Canvas>

functionLandOnSpace(sender, e) {  //on serverif (!ShipAnimateActive && !blnWaitingOnServer) {
    blnWaitingOnServer = true;
    RunServerFunction("/sqgame/getJSLLandOnSpace");
        ShowWaitingBox();
        };
else {
    alert('Waiting on server.');
};

}

Post a Comment for "Calling A Javascript Function From Silverlight"