-
-
Save NARKOZ/618682 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* HTMLParser for Greasemonkey by snaka(http://d.hatena.ne.jp/snaka72/) | |
* | |
* Original coode written by swdyh(http://d.hatena.ne.jp/swdyh/) | |
* This code includes part of AutoPagerize(http://userscripts.org/scripts/show/8551) | |
* | |
* Released under the GPL license | |
* http://www.gnu.org/copyleft/gpl.html | |
*/ | |
var HTMLStringToDOM = (function() { | |
function createHTMLDocumentByString(str) { | |
if (document.documentElement.nodeName != 'HTML') { | |
return new DOMParser().parseFromString(str, 'application/xhtml+xml') | |
} | |
var html = strip_html_tag(str) | |
var htmlDoc | |
try { | |
// We have to handle exceptions since Opera 9.6 throws | |
// a NOT_SUPPORTED_ERR exception for |document.cloneNode(false)| | |
// against the DOM 3 Core spec. | |
htmlDoc = document.cloneNode(false) | |
htmlDoc.appendChild(htmlDoc.importNode(document.documentElement, false)) | |
} | |
catch(e) { | |
htmlDoc = document.implementation.createDocument(null, 'html', null) | |
} | |
var fragment = createDocumentFragmentByString(html) | |
try { | |
fragment = htmlDoc.adoptNode(fragment) | |
} | |
catch(e) { | |
fragment = htmlDoc.importNode(fragment, true) | |
} | |
htmlDoc.documentElement.appendChild(fragment) | |
return htmlDoc | |
} | |
function createDocumentFragmentByString(str) { | |
var range = document.createRange() | |
range.setStartAfter(document.body) | |
return range.createContextualFragment(str) | |
} | |
function strip_html_tag(str) { | |
var chunks = str.split(/(<html(?:[ \t\r\n][^>]*)?>)/) | |
if (chunks.length >= 3) { | |
chunks.splice(0, 2) | |
} | |
str = chunks.join('') | |
chunks = str.split(/(<\/html[ \t\r\n]*>)/) | |
if (chunks.length >= 3) { | |
chunks.splice(chunks.length - 2) | |
} | |
return chunks.join('') | |
} | |
return createHTMLDocumentByString; | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment