1

We have this script which we want to run only if user agent is ReactSnap. I tried doing this but it does not seem to be working.

<script>
     if(navigator.userAgent!=='ReactSnap'){
        <script src='//cdnt.netcoresmartech.com/smartechclient.js'</script>
     }
</script>
SuleymanSah
  • 17,153
  • 5
  • 33
  • 54
horrible_nerd
  • 115
  • 3
  • 9
  • 2
    In this example you run this script if user agent is NOT ReactSnap. Probably your should use: `if(navigator.userAgent=='ReactSnap'){` – Roman Bush Nov 19 '19 at 10:45

4 Answers4

2

The operator you are using in your conditional statement - !== is checking to see if the condition is not true. The correct syntax is if(navigator.userAgent=="ReactSnap") You are also trying to write html in a javascript context.

You should create your script tag using javascript, like the below example:

if(navigator.userAgent=="ReactSnap"){ // check userAgent
    var script = document.createElement("script"); // create a script tag
    script.setAttribute("type","text/javascript"); // set type to js
    script.setAttribute("src", "//cdnt.netcoresmartech.com/smartechclient.js") // define src for script tag
    document.head.appendChild(script); // load script into document head, or change this to a specific location
}
Jonny
  • 1,053
  • 1
  • 13
  • 26
1

This solution waits to add the script element to the page until we know the condition is true (tested in Chrome):

<body>

  <div>Page content goes here</div>

  <script>
    let conditionalScript = document.createElement("script");
    conditionalScript.innerHTML = "alert('woo!')";
    // (But set .src instead of .innerHTML)

    let userAgent = 'ReactSnap';
    if(userAgent == 'ReactSnap'){
      // (But check `navigator.userAgent` instead of `userAgent`)
      document.querySelector("body").appendChild(conditionalScript);
    }
  </script>

</body>
Cat
  • 4,141
  • 2
  • 10
  • 18
0

I'd suggest using createElement, changing the source with setAttribute and appending it to the head like this.

if(navigator.userAgent!=='ReactSnap'){
  let smartTech = document.createElement('script');
  smartTech.setAttribute('src', '//cdnt.netcoresmartech.com/smartechclient.js');
  document.head.appendChild(smartTech);
}
TKTurbo
  • 92
  • 1
  • 11
0

You can try something like this:

<script>
    if(navigator.userAgent=='ReactSnap'){
          var script = document.createElement('script');
          script.src = "//cdnt.netcoresmartech.com/smartechclient.js";
          document.head.appendChild(script);

    }
</script>
Ankit Chugh
  • 198
  • 1
  • 11