2

I have multi script tags in one page and it's executed synchronously.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8"/>
    <title>Document</title>
    <script type="text/javascript">
     first
    </script>
  </head>
  <body>
    <div>test</div>
    <script type="text/javascript">
     alert('2')
    </script>
    <div>test</div>
    <script type="text/javascript">
     alert('3')
    </script>
    <div>test</div>
  </body>
</html>

I want to disable all of the following script tags such as alert(2), alert(3) and so on, how can I write js on first position ?

honmaple
  • 889
  • 1
  • 8
  • 12
  • Can the HTML be adjusted at all? Why is the first script in the `` and the others in the ``? – skyline3000 Jan 08 '18 at 04:01
  • https://stackoverflow.com/questions/9850317/how-do-you-disable-script-elements-using-javascript – orabis Jan 08 '18 at 05:18
  • Possible duplicate of [How do you disable – orabis Jan 08 '18 at 05:18
  • @skyline3000 I just took it as an example for disabling script tags but have no effect on other html tags. – honmaple Jan 09 '18 at 01:41
  • @orabis I think it's different, I just want to disable script tags under certain tag when them executed synchronously – honmaple Jan 09 '18 at 01:48
  • What you're asking for really can't be done. If your HTML has JavaScript in it, it is basically run as soon as it is parsed. You could try to do something like `scriptTag.innerHTML = ''` to remove all the text between the opening and closing tags, but again, the script has to already be loaded for you to know it's there, and once it's there, it will start executing. So, that would only work if you have static code (like variables and function definitions), not code that actually runs right away (like the `alert` function). – skyline3000 Jan 09 '18 at 02:25

2 Answers2

1

That is a strange question...
So I assume that the exact question is «How to disable a particular function, like alert()».

You can disable the function itself by replacing it with an empty function.

alert("I'm showing...");

var alert=function(){};

alert("I'm not showing");

And if you would like to restore it back later, you have to store it under another name in the first place:

alert("I'm showing...");

// Store the function under another name
var disabled_alert = alert;

// Disable it
var alert=function(){};

alert("I'm not showing");

// Restore it.
alert = disabled_alert;

alert("Hey! I'm back!!!");

You just can't disable "a script tag" (or its content), if you don't know the function names.

Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
0

I had use a void function if i were you.

<div>test</div>
<script type="text/javascript">
  function alert2() {
    alert('2')
  }
</script>
<div>test</div>
<script type="text/javascript">
   function alert3() {
     alert('3')
   }
</script>
<div>test</div>

And when you want to enable them, just execute your func alert2() or alert3().

Nuru Salihu
  • 4,756
  • 17
  • 65
  • 116