From 10fc59007d717432ea126e49ce4142e6c4d5136e Mon Sep 17 00:00:00 2001 From: Timmy Willison Date: Mon, 28 Mar 2016 10:32:15 -0400 Subject: [PATCH] Core: set the base href of the context in parseHTML Fixes gh-2965 Close gh-3022 --- src/core/parseHTML.js | 30 ++++++++++++++++++++++-------- test/unit/core.js | 9 +++++++++ 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/src/core/parseHTML.js b/src/core/parseHTML.js index 30405363c..260fd3ca7 100644 --- a/src/core/parseHTML.js +++ b/src/core/parseHTML.js @@ -21,14 +21,28 @@ jQuery.parseHTML = function( data, context, keepScripts ) { context = false; } - // Stop scripts or inline event handlers from being executed immediately - // by using document.implementation - context = context || ( support.createHTMLDocument ? - document.implementation.createHTMLDocument( "" ) : - document ); - - var parsed = rsingleTag.exec( data ), - scripts = !keepScripts && []; + var base, parsed, scripts; + + if ( !context ) { + + // Stop scripts or inline event handlers from being executed immediately + // by using document.implementation + if ( support.createHTMLDocument ) { + context = document.implementation.createHTMLDocument( "" ); + + // Set the base href for the created document + // so any parsed elements with URLs + // are based on the document's URL (gh-2965) + base = context.createElement( "base" ); + base.href = document.location.href; + context.head.appendChild( base ); + } else { + context = document; + } + } + + parsed = rsingleTag.exec( data ); + scripts = !keepScripts && []; // Single tag if ( parsed ) { diff --git a/test/unit/core.js b/test/unit/core.js index 7f58f489a..5bf3ab1d1 100644 --- a/test/unit/core.js +++ b/test/unit/core.js @@ -1563,6 +1563,15 @@ QUnit.test( "jQuery.parseHTML", function( assert ) { assert.ok( jQuery.parseHTML( "<#if>

This is a test.

<#/if>" ) || true, "Garbage input should not cause error" ); } ); +QUnit.test( "jQuery.parseHTML() - gh-2965", function( assert ) { + assert.expect( 1 ); + + var html = "", + href = jQuery.parseHTML( html )[ 0 ].href; + + assert.ok( /\/test\.html$/.test( href ), "href is not lost after parsing anchor" ); +} ); + if ( jQuery.support.createHTMLDocument ) { QUnit.asyncTest( "jQuery.parseHTML", function( assert ) { assert.expect( 1 ); -- 2.39.5