Inserting Javascript into DOM
You can add remote scripts to your integration through the vendor file
The following example walks through how you can load a remotely hosted script into your integration. A great example of this technique is the official Google Maps integration.
To start you will need to add a vendor.js
file to your integration config file.
Once you've updated your config, create the vendor.js
file in the appropriate location. In our example, we will be including the google maps API which is hosted by Google. We will need to include an API Key which we have configured as an option on the integration. Since we are using integration options as part of our code, we will need to implement the logic inside the onSettingsChange
method. This way, anytime the user updates their API key, we will be able to update the Google Maps API with the correct API Key value.
To start, we will declare a variable that will hold our API script object. In addition, we will register a function with the onSettingsChange
hook which will call our function initGoogleMaps
anytime the integration option values for the user change. The onSettingsChange
method will always be called once when the integration first loads in the client.
Next we'll need to implement our initGoogleMaps
method. The first thing we'll do is remove any previous version of the API that might be present. We check to see if the googleMapApiScript
variable has been previously set. If it has, we remove the script element that was set.
After ensuring that any previous script has been removed, we can add our script in. First we check to make sure the user has set an API Key option. If the option exists, we go ahead and insert our script into the head
element of the web page and save the resulting element.
The vendor.js
file is being run in the Overlay Window so adding a script to the head
of the document will modify the HTML for the Overlay Window itself.
The final vendor.js
file will look like this.
Last updated