Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/*
* 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
You can’t perform that action at this time.