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>
1
  • 2
    In this example you run this script if user agent is NOT ReactSnap. Probably your should use: if(navigator.userAgent=='ReactSnap'){ Commented Nov 19, 2019 at 10:45

4 Answers 4

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
}
Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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);
}

Comments

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.