Open In App

JQuery | globalEval() method

This globalEval() Method in jQuery is used to execute some JavaScript code globally.

Syntax:



jQuery.globalEval( code [, options ] )

Parameters: The globalEval() method accepts two parameter that is mentioned above and described below:

Return Value: It returns the boolean value.



Below examples illustrate the use of globalEval() method in jQuery:

Example 1: In this example, the globalEval() method executes a script in the global context.




<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JQuery | globalEval() method</title
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
  
</head>
<body style="text-align:center;"
      
    <h1 style="color: green"
        GeeksForGeeks 
    </h1
      
    <h3>JQuery | globalEval() method</h3>
    <p>Execute a script in the global context.</p>
    <p id = "geeks"> </p>
    <script>
    function GFG() {
      jQuery.globalEval( "var newVar = 'Shubham Singh'" );
      document.getElementById("geeks").innerHTML = newVar;
    }
    GFG();
    </script>
</body>
</html>                                                                                                    

Output:

Example 2: In this example, the globalEval() method executes a script with a nonce value on a site with Content Security Policy enabled.




<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JQuery | globalEval() method</title
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
  
</head>
<body style="text-align:center;"
      
    <h1 style="color: green"
        GeeksForGeeks 
    </h1
      
    <h3>JQuery | globalEval() method</h3>
    <p>Execute a script with a nonce value on a<br>
    site with Content Security Policy enabled.</p>
    <p id = "geeks"> </p>
    <script>
    function GFG() {
      jQuery.globalEval( "var variable = true;", {
    nonce: "nonce-2726c7f26c"
  } );
      document.getElementById("geeks").innerHTML = variable;
    }
    GFG();
    </script>
</body>
</html>                                                                                                                                            

Output:


Article Tags :