Solution 1 :

const script = document.getElementById("script_id");

if (script) {
    script.parentNode.removeChild(script);
}

Solution 2 :

helmet to dynamically inject scripts into the Html
document and to use useEffect to cleanup the injected scripts,like this

const component = () => {

useEffect (() => {

return () => {

document.getElementById("id_1").remove();
}
},[])

return(
<>
<Helmet>
<script src="..." id="id_1" />
</Helment>
   <div>
     hello world
   </div>
</>
)

}

this way the script is loaded only for the specific pages and not accessible for other pages.cheers!

Problem :

I’ve integrated a third-party chatbot with the help of script tag in the public/index.html.
But on some urls I don’t want to show the chatbot at all.

How can I remove the script tag depending on the url before/after it loads.

public/index.html:

     <body>
      <div id="root"></div>

      <script type="text/javascript">
        var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
        (function(){
        var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
        s1.async=true;
        s1.src='https://embed.tawk.to/<TOKEN_ID>/default';
        s1.charset='UTF-8';
        s1.setAttribute('crossorigin','*');
        s0.parentNode.insertBefore(s1,s0);
        })();
      </script>

    </body>

Comments

Comment posted by Pratap Sharma

Are you using with react??

Comment posted by gadi tzkhori

You can hide the bot element on location change in vanilla

Comment posted by Christian Fritz

which router are you using? Rather than removing it, I would only add it on the routes that need it. That’s much easier.

Comment posted by Sunil Kumar Singh

@PratapSharma yes using react 16.12.0

Comment posted by apokryfos

I don’t think you can do this. Once this script runs it includes the chatbot script and since react router routes change without page reloads the script will be loaded in memory and even if you remove the tag the chatbot will still be functioning. You should instead check the specific chatbot documentation on instructions on how to destroy it when you don’t need it

Comment posted by edit

Your answer could be improved with additional supporting information. Please

By