Skip to content

JavaScript Integration

pablocar80 edited this page Dec 30, 2020 · 11 revisions

Overview

One of the main reasons to execute JavaScript is to include 3rd party JavaScript tools and libraries.

Including JavaScript in web pages

There are different ways to include and execute JavaScript from Lara:

  • Include in your document <script> tags that references external JavaScript files
  • Include in your document <script> tags that directly contain JavaScript code
  • Call context.JSBridge.Submit(javaScriptCode) from your C# code

To use Lara to host your own JavaScript files, check out Publishing files.

The JSBridge.Submit method receives a string with code and passes it to the client to execute:

  • The client executes the code after the server has finished processing the event that yielded the Submit call.
  • If there is more than one JSBridge.Submit call, they will be executed in the order that they were created.

For more information about inserting JavaScript into HTML documents, check this page.

Triggering server-side events from JavaScript

It's possible to trigger server-side events from the client in JavaScript by calling LaraUI.sendMessage(...). This function receives an object with the following specification:

export interface MessageOptions {
    key: string;                // string that identifies the event
    data?: string;              // optional data string
    block?: boolean;            // optional: block the UI while sending?
    blockElementId?: string;    // optional: when blocking, block only a specific element
    blockHtml?: string;         // optional: override HTML shown when blocking
    longRunning?: boolean;      // optional: long-running event (version 0.5.11+)
}

export interface LaraUiInterface {
    sendMessage: (options: MessageOptions) => void;
}

// @ts-ignore
export const LaraUI = window['LaraUI'] as LaraUiInterface;

In order to listen on the server to these custom events, we register them with the method context.JSBridge.OnMessage.

Here is an example of a page that includes a button, and the button triggers a custom event:

class MyMessagePage : IPage
{
    public string Received { get; private set; }

    public Task OnGet()
    {
        var button = Element.Create("button", "mybutton");
        var text = new TextNode("test message");
        button.AppendChild(text);
        button.SetAttribute("onclick",
            "LaraUI.sendMessage( { key: 'hello', data: 'mydata' } );");
        LaraUI.Page.Document.Body.AppendChild(button);
        LaraUI.Page.JSBridge.OnMessage("hello", () =>
        {
            Received = LaraUI.Page.JSBridge.EventData;
            return Task.CompletedTask;
        });
        return Task.CompletedTask;
    }
}