Created
July 26, 2009 01:53
-
-
Save snaka/155402 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 = 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