Skip to content

Commit 10fc590

Browse files
committed
Core: set the base href of the context in parseHTML
Fixes jquerygh-2965 Close jquerygh-3022
1 parent 5cbb234 commit 10fc590

2 files changed

Lines changed: 31 additions & 8 deletions

File tree

src/core/parseHTML.js

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,28 @@ jQuery.parseHTML = function( data, context, keepScripts ) {
2121
context = false;
2222
}
2323

24-
// Stop scripts or inline event handlers from being executed immediately
25-
// by using document.implementation
26-
context = context || ( support.createHTMLDocument ?
27-
document.implementation.createHTMLDocument( "" ) :
28-
document );
29-
30-
var parsed = rsingleTag.exec( data ),
31-
scripts = !keepScripts && [];
24+
var base, parsed, scripts;
25+
26+
if ( !context ) {
27+
28+
// Stop scripts or inline event handlers from being executed immediately
29+
// by using document.implementation
30+
if ( support.createHTMLDocument ) {
31+
context = document.implementation.createHTMLDocument( "" );
32+
33+
// Set the base href for the created document
34+
// so any parsed elements with URLs
35+
// are based on the document's URL (gh-2965)
36+
base = context.createElement( "base" );
37+
base.href = document.location.href;
38+
context.head.appendChild( base );
39+
} else {
40+
context = document;
41+
}
42+
}
43+
44+
parsed = rsingleTag.exec( data );
45+
scripts = !keepScripts && [];
3246

3347
// Single tag
3448
if ( parsed ) {

test/unit/core.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1563,6 +1563,15 @@ QUnit.test( "jQuery.parseHTML", function( assert ) {
15631563
assert.ok( jQuery.parseHTML( "<#if><tr><p>This is a test.</p></tr><#/if>" ) || true, "Garbage input should not cause error" );
15641564
} );
15651565

1566+
QUnit.test( "jQuery.parseHTML(<a href>) - gh-2965", function( assert ) {
1567+
assert.expect( 1 );
1568+
1569+
var html = "<a href='test.html'></a>",
1570+
href = jQuery.parseHTML( html )[ 0 ].href;
1571+
1572+
assert.ok( /\/test\.html$/.test( href ), "href is not lost after parsing anchor" );
1573+
} );
1574+
15661575
if ( jQuery.support.createHTMLDocument ) {
15671576
QUnit.asyncTest( "jQuery.parseHTML", function( assert ) {
15681577
assert.expect( 1 );

0 commit comments

Comments
 (0)