Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: usage of DOMParser on mobile devices (iOS 7.*)

I'm using angular in my project. But it doesn't matter)

I have to use DOMParser to check and edit some data in one field (.Content)

And all was ok... I took iPad 3 with installed iOS 7 and was suprised...

Why DOMParser isn't working on iOS 7 (but works on iOS 8+)?

How can i solve this issue on iOS 7? Maybe there are some workarounds?

Here is part of my code:

var parser = new DOMParser();
var doc = parser.parseFromString('<div id="fetchContent">' + $scope.news.Content + '</div>', "text/html");
...
$scope.news.Content = doc.getElementById('fetchContent').innerHTML;

if i delete this code - app is working normally, but with DOMParser seems that it raise en error...

like image 533
brabertaser19 Avatar asked Nov 02 '15 07:11

brabertaser19


1 Answers

Certain browsers don't support this functionality. To patch this, we can use the following javascript code:

* inspired by https://gist.github.com/1129031 */
/*global document, DOMParser*/

(function(DOMParser) {
    "use strict";

    var
      proto = DOMParser.prototype
    , nativeParse = proto.parseFromString
    ;

    // Firefox/Opera/IE throw errors on unsupported types
    try {
        // WebKit returns null on unsupported types
        if ((new DOMParser()).parseFromString("", "text/html")) {
            // text/html parsing is natively supported
            return;
        }
    } catch (ex) {}

    proto.parseFromString = function(markup, type) {
        if (/^\s*text\/html\s*(?:;|$)/i.test(type)) {
            var
              doc = document.implementation.createHTMLDocument("")
            ;
                if (markup.toLowerCase().indexOf('<!doctype') > -1) {
                    doc.documentElement.innerHTML = markup;
                }
                else {
                    doc.body.innerHTML = markup;
                }
            return doc;
        } else {
            return nativeParse.apply(this, arguments);
        }
    };
}(DOMParser));

The above script was extracted from mozilla's website here.

like image 150
James Avatar answered Oct 06 '22 04:10

James