From: Michał Gołębiowski-Owczarek Date: Tue, 8 Dec 2020 10:22:21 +0000 (+0100) Subject: Core: Report browser errors in parseXML X-Git-Tag: 4.0.0-beta~149 X-Git-Url: https://source.dussan.org/?a=commitdiff_plain;h=8969732518470a7f8e654d5bc5be0b0076cb0b87;p=jquery.git Core: Report browser errors in parseXML Fixes gh-4784 Closes gh-4816 --- diff --git a/src/core/parseXML.js b/src/core/parseXML.js index 715f59f1f..482545aaf 100644 --- a/src/core/parseXML.js +++ b/src/core/parseXML.js @@ -2,7 +2,7 @@ import jQuery from "../core.js"; // Cross-browser xml parsing jQuery.parseXML = function( data ) { - var xml; + var xml, parserErrorElem; if ( !data || typeof data !== "string" ) { return null; } @@ -11,12 +11,17 @@ jQuery.parseXML = function( data ) { // IE throws on parseFromString with invalid input. try { xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); - } catch ( e ) { - xml = undefined; - } + } catch ( e ) {} - if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { - jQuery.error( "Invalid XML: " + data ); + parserErrorElem = xml && xml.getElementsByTagName( "parsererror" )[ 0 ]; + if ( !xml || parserErrorElem ) { + jQuery.error( "Invalid XML: " + ( + parserErrorElem ? + jQuery.map( parserErrorElem.childNodes, function( el ) { + return el.textContent; + } ).join( "\n" ) : + data + ) ); } return xml; }; diff --git a/test/unit/core.js b/test/unit/core.js index 6bcea95af..af355c621 100644 --- a/test/unit/core.js +++ b/test/unit/core.js @@ -1418,9 +1418,9 @@ QUnit.test( "jQuery.parseXML", function( assert ) { } try { xml = jQuery.parseXML( "

Not a <well-formed xml string

" ); - assert.ok( false, "invalid xml not detected" ); + assert.ok( false, "invalid XML not detected" ); } catch ( e ) { - assert.strictEqual( e.message, "Invalid XML:

Not a <well-formed xml string

", "invalid xml detected" ); + assert.ok( e.message.indexOf( "Invalid XML:" ) === 0, "invalid XML detected" ); } try { xml = jQuery.parseXML( "" ); @@ -1436,6 +1436,29 @@ QUnit.test( "jQuery.parseXML", function( assert ) { } } ); +// Support: IE 11+ +// IE throws an error when parsing invalid XML instead of reporting the error +// in a `parsererror` element, skip the test there. +QUnit.testUnlessIE( "jQuery.parseXML - error reporting", function( assert ) { + assert.expect( 2 ); + + var errorArg, lineMatch, line, columnMatch, column; + + sinon.stub( jQuery, "error" ); + + jQuery.parseXML( "

Not a <well-formed xml string

" ); + errorArg = jQuery.error.firstCall.lastArg.toLowerCase(); + console.log( "errorArg", errorArg ); + + lineMatch = errorArg.match( /line\s*(?:number)?\s*(\d+)/ ); + line = lineMatch && lineMatch[ 1 ]; + columnMatch = errorArg.match( /column\s*(\d+)/ ); + column = columnMatch && columnMatch[ 1 ]; + + assert.strictEqual( line, "1", "reports error line" ); + assert.strictEqual( column, "11", "reports error column" ); +} ); + testIframe( "document ready when jQuery loaded asynchronously (#13655)", "core/dynamic_ready.html",