2

i am creating website using nunjucks and express, its king of blog website and content coming from prismic. i want to load one script file for active campane form when user navigate from blog list page to any blog detail page, after navigate to detail page. will get script URL from prismic and I want to execute that script in HTML file.

its working while refresh the detail page but its not working when navigate from one page to another pages.

here is some sample code of my website

    ---
layout: _layout.njk
permalink: "/{{ post.blogType }}/{{ post.uid }}/"
pagination:
    alias: post
    data: posts
    size: 1
    addAllPagesToCollections: true
---

{% set params = item.primary.sumo_form_id.split("=") %}
        <div class="_form_{{params[1]}}">
        </div>
        <script src="{{item.primary.sumo_form_id}}" type="text/javascript" charset="utf-8" defer>
        </script>
KARNAV PARGI
  • 445
  • 1
  • 4
  • 15
Trushar Narodia
  • 3,511
  • 2
  • 11
  • 17

1 Answers1

0

After spent so much time i have found the solution. it is not proper solution but it is working right now.

Page where you are using recapcha. (njk file)

<div 
    id="recaptcha"
    data-callback="recaptchaOnload"
    data-sitekey="SITE_KEY"
    data-size="invisible"
    class="g-recaptcha"> 
</div>

index.njk

<head>
<script>
setInterval(()=>{
    recaptchaOnload(); // function calls every 20 Seconds.
}, 20000)

function recaptchaOnload() {
  try {
    if (document.getElementsByClassName("g-recaptcha").length > 0) {
      // Whenever route changes this function is going to check for id="g-recaptcha".
      // if its found recapcha code renders 
      grecaptcha.render("recaptcha", {
        sitekey: "SITE_KEY",
        callback: function () {
          console.log("recaptcha callback");
        },
      });
    }
  } catch (e) {
    return;
  }
}
</script>
<script src='https://www.google.com/recaptcha/api.js?onload=recaptchaOnload&render=explicit' async defer>
</head>

Q - Why i have to use this functionality ?

A - nunjucks are server side templates. so once they are initialised in front-end and if we have added scripts in other than parent route it is not going to initialised, if we changed to new page without redirect(page refresh). So in such conditions this is going to useful

KARNAV PARGI
  • 445
  • 1
  • 4
  • 15