Site Overlay

Guide: Use Javascript in Swift (Part 2)

Now that you have a Plugin class, let’s use it!


Previous: Create the Plugin class

Create a Javascript plugin – my_plugin.js
Our plugin here simply echoes any message it receives back to the host app.

// This function is called by our host app
function onmessage(data) {

    // Just pass all incoming messages back to the host app
    postMessage(data);

}

We first create a function called onmessage. This function is created in the global scope, so it will be found and used by our Plugin class. Then when it’s called, we simply echo back the data by calling the global postMessage function. The postMessage function was inserted into the global scope by the Plugin class as well.

Get the file URL to the Javascript file
Adding the guard around the variable is a good way of making sure the app doesn’t crash if for some reason the file can’t be found.

guard let fileURL = Bundle.main.url(forResource: "my_plugin", withExtension: "js") else {
    return
}

Create a Plugin instance and load our plugin
We pass in the URL to the plugin Javascript file to execute.

let plugin = Plugin(file: fileURL)

Add a message handler
We need to now add our own code for what must happen when the plugin sends the host app a message. In our case, let’s just output it to the console.

plugin.onmessage = { (data) in
    print("Message received: \(data)")
}

That’s it!
You can see full code and an example here.