Sha256: 274012b64e0324bba3faf11da6296af11ca00615abc99228aaea7e037a9bc65a

Contents?: true

Size: 1.99 KB

Versions: 4

Compression:

Stored size: 1.99 KB

Contents

/* global XMLHttpRequest */
window.GOVUK = window.GOVUK || {}
window.GOVUK.Modules = window.GOVUK.Modules || {};

(function (Modules) {
  function SinglePageNotificationButton ($module) {
    this.$module = $module
    this.basePath = this.$module.querySelector('input[name="base_path"]').value
    this.buttonLocation = this.$module.getAttribute('data-button-location')

    this.personalisationEndpoint = '/api/personalisation/check-email-subscription?base_path=' + this.basePath
    // This attribute is passed through to the personalisation API to ensure the updated button has the same button_location for analytics
    if (this.buttonLocation) this.personalisationEndpoint += '&button_location=' + this.buttonLocation
  }

  SinglePageNotificationButton.prototype.init = function () {
    var xhr = new XMLHttpRequest()
    xhr.open('GET', this.personalisationEndpoint, true)

    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        var responseText = xhr.responseText
        // if response text exists and is JSON parse-able, parse the response and get the button html
        if (responseText && this.responseIsJSON(responseText)) {
          var newButton = JSON.parse(responseText).button_html
          var html = document.createElement('div')
          html.innerHTML = newButton
          // test that the html returned contains the button component; if yes, swap the button for the updated version
          var responseButtonContainer = html.querySelector('form.gem-c-single-page-notification-button')
          if (responseButtonContainer) {
            this.$module.parentNode.replaceChild(responseButtonContainer, this.$module)
          }
        }
      }
    }.bind(this)
    xhr.send()
  }

  SinglePageNotificationButton.prototype.responseIsJSON = function (string) {
    try {
      JSON.parse(string)
    } catch (e) {
      return false
    }
    return true
  }
  Modules.SinglePageNotificationButton = SinglePageNotificationButton
})(window.GOVUK.Modules)

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
govuk_publishing_components-27.17.0 app/assets/javascripts/govuk_publishing_components/components/single-page-notification-button.js
govuk_publishing_components-27.16.0 app/assets/javascripts/govuk_publishing_components/components/single-page-notification-button.js
govuk_publishing_components-27.15.0 app/assets/javascripts/govuk_publishing_components/components/single-page-notification-button.js
govuk_publishing_components-27.14.2 app/assets/javascripts/govuk_publishing_components/components/single-page-notification-button.js