Skip to content

commento.js: reinit function for SPAs

Wesley Bos requested to merge wezzle/commento:feat-reinit into master

Adds a reInit function to the global namespace that can be used by Single Page Applications to reinit commento with different options.

We are currently using this in combination with Gatsby. When changing blog page the browser does not reload but simple re-renders the new page. We need to be able to reload commento with a new pageId without reloading the entire js file. The function in this PR does that.

Please let me know if you require anything else for a valid pull request.

I couldn't find the repo for docs.commento.io but if you point me in the right direction I could add a paragraph about Single Page Applications and add the following react example:

import React, { useEffect } from 'react'

const Commento = ({ pageId }) => {
  useEffect(() => {
    if (typeof window !== 'undefined' && !window.commento) {
      // init empty object so commento.js script extends this with global functions
      window.commento = {}
      const script = document.createElement('script')
      // Replace this with the url to your commento instance's commento.js script
      script.src = `http://localhost:8080/js/commento.js`
      script.defer = true
      // Set default attributes for first load
      script.setAttribute('data-auto-init', false)
      script.setAttribute('data-page-id', pageId)
      script.setAttribute('data-id-root', 'commento-box')
      script.onload = () => {
        // Tell commento.js to load the widget
        window.commento.main()
      }
      document.getElementsByTagName('head')[0].appendChild(script)
    } else if (typeof window !== 'undefined' && window.commento) {
      // In-case the commento.js script has already been loaded reInit the widget with a new pageId
      window.commento.reInit({
        pageId: pageId,
      })
    }
  }, [])

  return <div id="commento-box" />
}

export default Commento

Merge request reports