Open In App

JQuery | globalEval() method

Last Updated : 27 Apr, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • code: This parameter is the JavaScript code to execute.
  • options => nonce : This parameter is the nonce attribute passed to the executed script.

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
  
</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
  
</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:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads