From feea9394b75a5dcb16fad013a402b388f97cefba Mon Sep 17 00:00:00 2001 From: Rick Waldron Date: Wed, 3 Apr 2013 11:26:07 -0400 Subject: [PATCH] Fixes #13714. jQuery.globalEval gotcha w/ strings that contain valid, prologue position strict mode pragma Signed-off-by: Rick Waldron --- src/core.js | 23 +++++++++++++++++++---- test/unit/core.js | 8 ++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/src/core.js b/src/core.js index cae3a90e3..e37627459 100644 --- a/src/core.js +++ b/src/core.js @@ -515,10 +515,25 @@ jQuery.extend({ noop: function() {}, // Evaluates a script in a global context - globalEval: function( data ) { - var indirect = eval; - if ( jQuery.trim( data ) ) { - indirect( data + ";" ); + globalEval: function( code ) { + var script, + indirect = eval; + + code = jQuery.trim( code ) + ";"; + + if ( code ) { + // If the code includes a valid, prologue position + // strict mode pragma, execute code by injecting a + // script tag into the document. + if ( code.indexOf("use strict") === 1 ) { + script = document.createElement("script"); + script.text = code; + document.head.appendChild( script ).parentNode.removeChild( script ); + } else { + // Otherwise, avoid the DOM node creation, insertion + // and removal by using an indirect global eval + indirect( code ); + } } }, diff --git a/test/unit/core.js b/test/unit/core.js index 7c840993b..6cdd3b93d 100644 --- a/test/unit/core.js +++ b/test/unit/core.js @@ -215,6 +215,14 @@ test( "globalEval", function() { equal( window.globalEvalTest, 3, "Test context (this) is the window object" ); }); +test( "globalEval with 'use strict'", function() { + expect( 1 ); + Globals.register("strictEvalTest"); + + jQuery.globalEval("'use strict'; var strictEvalTest = 1;"); + equal( window.strictEvalTest, 1, "Test variable declarations are global (strict mode)" ); +}); + test("noConflict", function() { expect(7); -- 2.39.5