From 48e44edfd0a8a7a29aa8fad39638ac0ee5243f42 Mon Sep 17 00:00:00 2001 From: Raymond Zhou Date: Mon, 19 Mar 2018 02:42:23 -0400 Subject: Pass HTML responses as plain-text in rails-ujs Running HTML responses through `DOMParser#parseFromString` results in complete `HTMLDocument` instances with unnecessary surrounding tags. For example: new DOMParser().parseFromString('

hello

', 'text/html') Will output:

hello

This is passed to the `ajax:success` handler as `event.detail[0]` (`data`), but cannot be used directly without first traversing the document. To resolve this, only XML content is passed through `parseFromString`, while HTML content is treated as plain-text. This matches the behavior of jquery-ujs, which relied on jQuery's response-type inference. --- actionview/app/assets/javascripts/rails-ujs/utils/ajax.coffee | 2 +- actionview/test/ujs/public/test/call-remote.js | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) (limited to 'actionview') diff --git a/actionview/app/assets/javascripts/rails-ujs/utils/ajax.coffee b/actionview/app/assets/javascripts/rails-ujs/utils/ajax.coffee index 2a8f5659e3..cf31c796df 100644 --- a/actionview/app/assets/javascripts/rails-ujs/utils/ajax.coffee +++ b/actionview/app/assets/javascripts/rails-ujs/utils/ajax.coffee @@ -69,7 +69,7 @@ processResponse = (response, type) -> script.nonce = cspNonce() script.text = response document.head.appendChild(script).parentNode.removeChild(script) - else if type.match(/\b(xml|html|svg)\b/) + else if type.match(/\bxml\b/) parser = new DOMParser() type = type.replace(/;.+/, '') # remove something like ';charset=utf-8' try response = parser.parseFromString(response, type) diff --git a/actionview/test/ujs/public/test/call-remote.js b/actionview/test/ujs/public/test/call-remote.js index 5932195363..8a88471982 100644 --- a/actionview/test/ujs/public/test/call-remote.js +++ b/actionview/test/ujs/public/test/call-remote.js @@ -128,6 +128,17 @@ asyncTest('execution of JS code does not modify current DOM', 1, function() { }) }) +asyncTest('HTML content should be plain-text', 1, function() { + buildForm({ method: 'post', 'data-type': 'html' }) + + $('form').append('') + $('form').append('') + + submit(function(e, data, status, xhr) { + ok(data === '

hello', 'returned data should be a plain-text string') + }) +}) + asyncTest('XML document should be parsed', 1, function() { buildForm({ method: 'post', 'data-type': 'html' }) -- cgit v1.2.3