Execute JavaScript from a Widget

Hello community,

This may sound silly but I couldn't accomplish this so far, not completely at least. Here's the thing. I have a simple HTML/Javascript schema that I want to make it work:

  • I've created a Widget with a workaround where I set a basic HTML (in the Content section), basically I just have a <head> section with a single reference to my Javascript file, something like:

<head><script type="text/javascript" src="res/myJavascript.js"></script></head>

  • And on the body section I just need to call a function where all the magic happens:

<body style='margin-left: 0px;'>

Now, "res" is a folder on the server of course so every change we need to do, needs to be done on the back end and that's not reasonable. The wording is also handled in that Javascript file and we need to be able to support different languages and with this approach its more difficult to do that.

So, my question is, how we could move from this back end approach to a front end where we have everything on the Widget, the Javascript code, Resources, etc. Thanks in advance.



  • Hi Marcelo. As I understand, you have a JavaScript file with a method in it which you want to call in the widget? If so, the approach is fairly straightforward.

    In a nutshell:

    • In Widget Studio, attach your JavaScript file to the widget. This makes it part of the widget, instead of needing to exist in a folder on the server. Any attached widget files are bundled with the widget if it is exported or imported, as well.
    • Get a URL reference to the JavaScript file from the widget so that it can be loaded. There's an API for that. So, if you attached a script called myJavascript.js, you'd use $core_v2_widget.GetFileUrl('myJavascript.js'), which gets a full URL for it.
    • Reference the script from the widget in a performant way so that it is only loaded once with #registerEndOfPageHtml() with a unique key and a <script src> tag referencing the script's URL.
    • Then set up a second #registerEndOfPageHtml() that contains <script> block in which you call the function defined by your script.

    Something like

      <script src="$core_v2_encoding.HtmlAttributeEncode($core_v2_widget.GetFileUrl('myJavascript.js'))"></script>
      <script type="text/javascript">
          // assuming myFunction_load is defined by your script

    This is a brief summary, but there's more detail here, including next steps for you can also use AJAX.

    Since you mention resources, you may be interested in using the built-in support for localization with widget resources instead of editing hardcoded resources in a JavaScript file. The benefit would be that it 1) should be simpler and 2) would respect whatever language the user has selected in their options.

    Language-specific resource key/value pairs are defined within the widget in Widget Studio

    And then they can be retrieved for use in the widget in the accessing user's preferred language using the API: