Permalink
Browse files

Merge pull request #175 from reednj77/domparser

Handle DOMParser exception
  • Loading branch information...
dhh committed Feb 3, 2013
2 parents 39764bc + 297f71f commit 16d3c8567299a04120feb54abb3537e2ea74a861
Showing with 25 additions and 7 deletions.
  1. +25 −7 lib/assets/javascripts/turbolinks.js.coffee
@@ -158,20 +158,38 @@ browserCompatibleDocumentParser = ->
createDocumentUsingParser = (html) ->
(new DOMParser).parseFromString html, 'text/html'
+ createDocumentUsingDOM = (html) ->
+ doc = document.implementation.createHTMLDocument ''
+ doc.documentElement.innerHTML = html
+ doc
+
createDocumentUsingWrite = (html) ->
doc = document.implementation.createHTMLDocument ''
doc.open 'replace'
doc.write html
doc.close()
doc
- if window.DOMParser
- testDoc = createDocumentUsingParser '<html><body><p>test'
-
- if testDoc?.body?.childNodes.length is 1
- createDocumentUsingParser
- else
- createDocumentUsingWrite
+ # Use createDocumentUsingParser if DOMParser is defined and natively
+ # supports 'text/html' parsing (Firefox 12+, IE 10)
+ #
+ # Use createDocumentUsingDOM if createDocumentUsingParser throws an exception
+ # due to unsupported type 'text/html' (Firefox < 12, Opera)
+ #
+ # Use createDocumentUsingWrite if:
+ # - DOMParser isn't defined
+ # - createDocumentUsingParser returns null due to unsupported type 'text/html' (Chrome, Safari)
+ # - createDocumentUsingDOM doesn't create a valid HTML document (safeguarding against potential edge cases)
+ try
+ if window.DOMParser
+ testDoc = createDocumentUsingParser '<html><body><p>test'
+ createDocumentUsingParser
+ catch e
+ testDoc = createDocumentUsingDOM '<html><body><p>test'
+ createDocumentUsingDOM
+ finally
+ unless testDoc?.body?.childNodes.length is 1
+ return createDocumentUsingWrite
installClickHandlerLast = (event) ->

0 comments on commit 16d3c85

Please sign in to comment.