What steps can I take to ensure that my Onetrust consent script is properly loaded before implementing Facebook pixel tracking in NextJS?

Looking for a solution to load my Cookies consent script as the first script in our NextJS application. The problem arises because we have Facebook pixel tracking implemented and they use parentNode.insertBefore which places their script on top.

This is how we are using Facebook pixel, following their documentation:

const html = [
  "!function(f,b,e,v,n,t,s)",
  "{if(f.fbq)return;n=f.fbq=function(){n.callMethod?",
  "n.callMethod.apply(n,arguments):n.queue.push(arguments)};",
  "if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';",
  "n.queue=[];t=b.createElement(e);t.async=!0;",
  "t.src=v;s=b.getElementsByTagName(e)[0];",
  "s.parentNode.insertBefore(t,s)}(window,document,'script',",
  "'https://connect.facebook.net/en_US/fbevents.js');",
  `fbq('init', '111222333');`,
  "fbq('track', 'PageView');",
  `fbq('init', '1234');`,
  "fbq('track', 'PageView');",
].join("");

const DocumentFacebookPixel = () => (
  <>
    <script key="track-fb-pixel" dangerouslySetInnerHTML={{ __html: html }} />
  </>
);

export default DocumentFacebookPixel;

Here is the OneTrust code implementation:

 const DocumentOneTrust = () => {
  return (
	<>
      <script
        src="https://url.com"
        type="text/javascript"
        charSet="UTF-8"
        data-domain-script="id-123-4"
      ></script>

      <script type="text/javascript">{function OptanonWrapper() {}}</script>
    </>
  );
};

export default DocumentOneTrust;

I have loaded the OneTrust script component before the Facebook pixel like this:

class Document extends NextDocument {
  render() {
    return (
      <Html>
        <NextHead>
         <DocumentOneTrust />
        </NextHead>
        <body>
          <Main />
          <NextScript />
          <DocumentFacebookPixel />
        </body>
      </Html>
    );
  }
}

Answer №1

We have implemented an _app.tsx file to manage this process efficiently. Initially, we perform a check to see if the onetrust window is active or if the opt-in cookie is already set. Only when one of these conditions is met, our script (which utilizes Google Tag Manager) gets included.

function App({ Component, pageProps }: AppProps) {
 const [injectScript, setInjectScript] = useState(false);
 useEffect(() => {
  if (typeof window !== 'undefined' && !window.OptanonWrapper) {
   window.OptanonWrapper = () => {
    window.OneTrust.OnConsentChanged(() => {
      if (window.OptanonActiveGroups.indexOf('C0004') > -1) {
        setInjectScript(true);
      }
    });
   };
  }

  if (typeof window !== 'undefined' &&
   document.cookie.replace(/(?:(?:^|.*;\s*)OptanonConsent\s*=\s*([^;]*).*$)|^.*$/, '$1').indexOf('C0004') > -1) {
    setInjectScript(true);
   }
  }, []);

 return (
   <GTMProvider state={{ injectScript, ...gtmParams }}>
    <Component {...pageProps} />
   </GTMProvider>
 );
}

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

Execute Javascript to close the current window

When I have a link in page_a.php that opens in a new tab using target="_blank". <a href="page_b.php" target="_blank">Open Page B</a> In page B, there's a script to automatically close the tab/window when the user is no longer viewing it: ...

Apply Jquery to add emphasis to every item on the list

Can someone help me with this assignment? I need to create a jQuery function that italicizes all list elements on the page when triggered by the client. Here is my current approach: $(document).ready(function() { $("li").click(function() { ...

Utilizing $.each to dynamically add data to a jQuery Mobile listview

Trying to implement a data reading mechanism using ajax resulted in unexpected html tag generation for <ul> <li>. The code snippet is as follows: (function( $, undefined ) { $(document).on("pagecreate", ".jqm-demos", function(){ ...

What is the best way to combine two arrays of objects in AngularJS?

How can I merge the existing object array with another one in AngularJS to implement the "load more" feature? Specifically, I want to add the AJAX response to the existing data each time. Currently, I have a variable called $scope.actions that holds the ...

Using React hooks to transfer an item from one array to another and remove it

export default function ShoppingCart() { const classes = useStyle(); const { productsList, filteredProductsList, setFilteredProductsList, setProductsList, } = useContext(productsContext); const [awaitingPaymentList, setAwaitingPaymentList] = us ...

Can the image upload file size be customized or adjusted?

Recently, I've come across a standard input file code that looks like this: <Label class="custom-file-upload"> <input type="file" onChange={onDrop} /> Upload Photo </Label> I have been thinking about limiting the size of the ...

Inconsistent behavior between Chrome and Firefox when using AngularJS $resource GET method: success in Chrome but error

I am currently working on a simple custom GET request in Angular using $resource angular.module('myApp') .factory('MyService', function($resource){ return $resrouce('some url', {}, { list: {method:'G ...

Randomize checkbox selection using Javascript and Bootstrap

I'm in a bit of a bind with my webpage and could really use some help to figure it out. Here's the issue: On my website, there's a table of players. Each player has two checkboxes on their line: one to show if they are active (checked), and ...

Ways to efficiently group and aggregate data in JavaScript, inspired by LINQ techniques

I'm feeling overwhelmed by this. Could you lend a hand? Consider the following .NET classes: Teacher: public class Teacher { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } publ ...

Enhance the sent server parameters by including extra options in fineuploader

I have successfully implemented file uploads using . Everything works perfectly. I am able to set parameters in the request object to send additional data to the server. However, when I try to add another parameter dynamically using the setParams function ...

Navigating through a diagonal path

Struggling to craft a diagonal navigation system similar to the images below. Despite its seemingly simplicity, I'm stuck investing too much time in figuring it out. My goal is for the menu container to smoothly reveal from right to left when clicking ...

The functionality of the delete button in Material UI Chip seems to be malfunctioning

I am working on mapping Material UI Chips, but I am facing an issue where the cross button is not showing up and I cannot click on them or use the onTouchTap event. Below is my mapping: {mapping.map(chipMap => { return ( <div> ...

Attempting to iterate through the div in order to collect all of the checkboxes and assign a label to each one

I am attempting to modify a piece of JavaScript code in order to locate all checkboxes, assign names to them, and then add label attributes with CSS for accessibility purposes. Here is the snippet of my existing code: <tr class="el-table__row" ...

Utilizing the principles of object orientation in Javascript to enhance event management

After attempting to modularize my JavaScript and make it object oriented, I found myself struggling when dealing with components that have multiple instances. This is an example of how my code currently looks: The HTML file structure is as follows: & ...

"Facing a dilemma with Javascript's Facebox getElementById function - not fetching any

Utilizing facebox, I am initiating a small modal dialog with a form and attempting to retrieve the value from a text field on that form using javascript. Below is the HTML code: <div id="dialog-form95" style="display:none"> <div class="block"> ...

Converting plain text to a JSON object using JavaScript: A step-by-step guide

Having trouble converting plain text into JSON value in Javascript. Need some assistance. Actual string obtained from a command line executed through Javascript: Net State: OFFLINE Net Err: Net Time: 0 Current Sample: 0 Sample #0 Sample Role: O ...

AngularJS textbox validation for numbers and required in repeating mode ensures that the user input is a

For more information, please visit the following link: https://plnkr.co/edit/9HbLMBUw0Q6mj7oyCahP?p=preview var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope) { $scope.NDCarray = [{val: '' ...

Switching the dialogue with no need for a refresh

I am working on a feature for my website where I want to switch the language seamlessly without having to reload the page when a user clicks on one of three language flags (German, French, and English). When a flag is clicked, I store a cookie called lang ...

Having trouble getting the JavaScript slider to animate

My code works perfectly in Codepen but when I try to implement it on my website, it shows as a static image. You can view the code here: https://codepen.io/anon/pen/zPMKpv I'm using the exact same code on my website located at: Does anyone have any ...

What is causing the label's color to remain the same?

Once the page has loaded, the label color (which reads "enter your name") is supposed to change to red. However, despite the script being in place, the color remains unchanged. What could be the reason for this? SCRIPT window.onload = initiateScript; fu ...