Scripting

The content of this page only applies to templates used within:

  • Product Recommendations

  • Onsite Content Personalization

  • Pop-Ups

Nosto campaign templates support two ways to define JavaScript script elements as part of the templates.

In the legacy mode, the script contents are evaluated in the scope of the nosto iframe and can refer to the main window via the global _targetWindow variable.

To support ES module loading in placement and popup script elements, the client script supports the usage of script[type='module'] elements in both of these contexts. This newer module mode is evaluated in the main window but uses module scope for sandboxing. To write variables to the global scope, you will need to do so explicitly by declaring fields in the window object.

For new accounts, we recommend the use of ES module scripts. For older accounts with existing templates, the legacy script mode works as well, but interaction with the main window is a bit more verbose.

The differences between the two modes are summarized here:

Legacy scripts

  • Syntax: <script>...</script>

  • Loaded into the nosto iframe sandbox

  • Access to the site window happens via the _targetWindow variable

  • Helper modules in the nosto window namespace are available without a prefix

Module scripts

  • Syntax: <script type="module">...</script>

  • Loaded as sandboxed modules into the site window

  • Site window contents are directly available, e.g., jQuery

  • Helper modules in the nosto window namespace are available via the nosto. prefix

Examples

<script>
  _targetWindow.jQuery(
</script>

becomes

<script type="module">
  jQuery(
</script>

Additionally, module scripts support:

Import syntax

<script type="module">
  import { createApp } from 'https://unpkg.com/petite-vue?module'
  createApp().mount()
</script>

Top-level await

<script type="module">
  const response = await fetch('http://www.acme.com/myapi/myresource')
  // Do something with the response
</script>

Lightweight sandboxing

<script type="module">
  // Config is not written to the window namespace but scoped to the script tag
  const config = {
    key: "738209438"
  }
</script>

Further reading

JavaScript modules

Last updated

Was this helpful?