Utilizing mailerlite popups within a Next.js application: A step-by-step guide

Trying to include a mailerlite popup in a client's next.js project has been quite challenging for me. I am struggling to convert the JavaScript snippets into jsx in order to make the popups work smoothly. Everything seems to function properly on initial load, but upon reload, I am encountering an error message:

window is not defined

The issue arises during DOM manipulation, and it appears that I require the window object based on the code provided in the snippet.

To integrate this Javascript snippet onto every page of your website just before the closing tag, you only need to add it once, even if you have multiple webforms:

<!-- MailerLite Universal -->
<script>
(function(m,a,i,l,e,r){ m['MailerLiteObject']=e;function f(){
var c={ a:arguments,q:[]};var r=this.push(c);return "number"!=typeof r?r:f.bind(c.q);}
f.q=f.q||[];m[e]=m[e]||f.bind(f.q);m[e].q=m[e].q||f.q;r=a.createElement(i);
var _=a.getElementsByTagName(i)[0];r.async=1;r.src=l+'?v'+(~~(new Date().getTime()/1000000));
_.parentNode.insertBefore(r,_);})(window, document, 'script', 'https://static.mailerlite.com/js/universal.js', 'ml');

var ml_account = ml('accounts', '912433', 'd5p1f7l9g0', 'load');
</script>
<!-- End MailerLite Universal -->

I have added this code to my Layout wrapper. While it functions correctly on first load, the aforementioned error pops up as soon as the user navigates to a new page.

PS I came across an old question related to this topic here, but it does not fully align with my current situation. I am looking to find a way to adapt the above snippet for use with nextjs. Any assistance would be greatly appreciated.

Answer №1

This method adopts a unique strategy by treating the MailerLite universal tag as a separate <script> hosted on your website's domain.

  1. Begin by incorporating a NextJS custom document.
  2. Develop a JavaScript file that contains the MailerLite universal tag code within the ./public directory. I personally stored mine in ./public/scripts/ml.js.
  3. Include a <script> tag to load #2 in your custom _document.js file:
import Document, { Html, Head, Main, NextScript } from 'next/document'

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx)
    return { ...initialProps }
  }

  render() {
    return (
      <Html>
        <Head>
          <script async src="/scripts/ml.js"></script>
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

export default MyDocument

Following these steps led to successful implementation! (Note: This was tested with embedded forms only).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why does everything seem to move in sync with the table's scrolling?

I recently had an issue resolved that fixed most of my concerns: I needed to make three separate edits, and now when I reintroduce the other two edits, they are included within the table section and scroll along with the table instead of being stuck beneat ...

Utilizing JavascriptExecutor in Selenium Webdriver to start playing a video

Is it possible to trigger the play function in a page's JavaScript jQuery code using JavascriptExecutor? Below is an example of code extracted from a website: <script type="text/javascript"> jQuery(document).ready(function($) { $('#wp_mep ...

Differences between visibility property manipulation in HTML and JS

One issue I am facing is that when I add a hidden property to a button in the HTML, it remains invisible. <button id="proceed_to_next_question" hidden> Next Question </button> However, if I remove the hidden property and include the following ...

Optimal row settings for different reports using Material-UI table pagination

Recently, I've been exploring an example involving material-ui's TablePagination. In this scenario, they present a useTable component with the following code snippet: import React, { useState } from 'react' import { Table, TableHead, Ta ...

"Exploring the new features of Next.js 13: Server-side actions

In my current project using Nextjs 13 and server actions, there is a form in place: const [isUploadingDocs, setIsUploadingDocs] = useState<boolean>(false); ... remaining code ... return ( <form action={async (formData) => { setIsUploadingDo ...

What is the best way to accomplish this in Next.js?

I am working on a NextJs application and I need to include a new route /cabinet with its own navigation. The challenge is that the application already has a navigation bar defined in _app.js. Is it possible to create a similar setup like _app.js for /cab ...

Updating a database with a loop of React Material UI toggle switches

I am trying to implement a material UI switch feature that can update the Active and De-Active status of users in the database directly from the Admin Panel. Currently, the database updates are functioning correctly when toggling the switches. However, th ...

Is query result caching implemented in the Next.js API route?

I have a Next.js application that is connected to a third-party API in order to display certain information. The data is retrieved through Next.js API routes, and the code for this can be found in /pages/api/data.js. const handler = async (req, res) => ...

Resolving issues with jQuery's live() method while incorporating AJAX calls

One of the challenges I'm facing is with buttons on a webpage that are part of the class "go". The code snippet below demonstrates how I handle actions related to these buttons: $(".go").live('click', this.handleAction); The issue arises w ...

Prevent users from navigating back in their browser with jQuery

As I work on developing an online testing app, one of the requirements is to prevent users from refreshing the page or going back during the test until it has ended. While I have successfully disabled the refresh action in jQuery using various methods with ...

The localhost is not updating on subsequent runs of npm run dev after the initial run

Every time I launch npm run dev (for my nextjs application), it functions properly on the initial run. However, after making modifications to my files, saving them, and checking my localhost, the changes do not appear. What is the solution? Currently, I f ...

Is there a way for me to access the user's gender and birthday following their login using their Google account details?

I have successfully implemented a Google sign-in button in my Angular application following the example provided in Display the Sign In With Google button: <div id="g_id_onload" class="mt-3" data-client_id="XXXXXXXXXXXX-XX ...

A guide on sorting JSON data with Javascript/jquery

I have a set of JSON data: {"X1":"3","X2":"34","Y1":"23","Y2":"23","Z1":"234","Z2":"43",...} My goal is to rearrange and group this data as follows: var newDataJson1 = { "X":{"X1":"3","X2":34}, "Y":{"Y1":"23","Y2":"23"}, ... } ALSO, I want to stru ...

The auto-refresh feature of DataTables is not functioning as expected

Having trouble with the reload feature of DataTables. This is the code I'm using to load and reload the table on the server-side: $( document ).ready(function() { $('#dienst_tabelle').DataTable( { "ajax": "getData ...

Can you provide an alternative code to access an element with the id of 'something' using vanilla JavaScript instead of jQuery's $('#something') syntax

Why am I seeing different console output for $('#list') and document.getElementById("list")? Here is the console printout: console.log($('#list')); console.log(document.getElementById("list")); However, the actual output in the cons ...

Transmit data to a modal using JSX mapping technique

When working with a map that renders multiple items, how can I efficiently pass parameters like the item's name and ID to a modal component? render(){ return( <div> <Modal isOpen={this.state.OpenDel ...

The JSON output is not displaying correctly

I've been attempting to utilize JSON.stringify in order to format my json object for better readability. However, it doesn't seem to be working as expected. Can someone please offer assistance in identifying what I might have done incorrectly? ...

Is it necessary to download and install plotly if I am using the cdn in my HTML file?

I'm currently developing an online application using Flask. The user input is collected with d3.js and sent to app.py, where it is used for an API call to retrieve the necessary data. This data is then returned in JSON format to JavaScript for renderi ...

Issue detected in React Rollup: the specific module 'name' is not being exported from the node_modules directory

Currently in the process of creating a library or package from my component. The tech stack includes React, Typescript, and various other dependencies. Encountering an error while using Rollup to build the package: [!] Error: 'DisplayHint' is ...

Transclusion with multiple slots in AngularJS

Attempting to incorporate a component in AngularJS 1.5.8 with multi-slot transclusion. The test performs well when utilizing a directive, however, with a component, it appears that the slot cannot be located!. This is how the component is declared app. ...