I have an extension I use privately that on occasion needs turn a svg document to a html document.
If I detect that the page does not contain a body element and that the location.href
contains the text ".svg" (the document is a SVG document) I try the following
document.removeChild(document.firstChild);
var body = document.createElement("body")
var html = document.createElement("html");
html.appendChild(document.createElement("head"));
html.appendChild(body);
document.appendChild(html);
Which seems to work. Inspecting the page shows a standard document
<html>
<head></head>
<body></body>
</html>
But when I try to access document.body.style
I get a null referance error. document.body
is equal to null
Fair enough I then try to set the document.body
element directly with
// leading on from first snippet
document.body = body; // line 8712
and I get a Uncaught TypeError: Failed to set the 'body' property on 'Document': The provided value is not of type 'HTMLElement'. at contentscript.js:8712
Uncaught TypeError: Failed to set the 'body' property on 'Document': The provided value is not of type 'HTMLElement'. at contentscript.js:8712
I just can not seem to create a useable HTML document from an empty document. Is it possible?
I really need the page as redirecting will remove the domain and associated session.
See http://alohci.net/static/Blindman67_1.svg which uses
<svg xmlns="http://www.w3.org/2000/svg">
<script type="application/ecmascript">
document.removeChild(document.firstChild);
var body = document.createElementNS("http://www.w3.org/1999/xhtml", "body")
var html = document.createElementNS("http://www.w3.org/1999/xhtml", "html");
html.appendChild(document.createElementNS("http://www.w3.org/1999/xhtml", "head"));
html.appendChild(body);
document.appendChild(html);
var i = document.createElementNS("http://www.w3.org/1999/xhtml", "i");
i.appendChild(document.createTextNode("Italic text"));
document.body = body; // Needed for Firefox. Not needed for Chrome
document.body.appendChild(i);
</script>
</svg>
to put the elements in the correct namespace.
document.createElement() in an SVG document (ie a non-XHTML, XML document) will create the elements in the null namespace where as you need them in the HTML namespace.
Here's what I use:
{
let cENS=document.createElementNS.bind(document,"http://www.w3.org/1999/xhtml"), //For the namespace URI, there's also `document.lookupNamespaceURI(null);`.
html=cENS("html"),head=cENS("head"),body=cENS("body");
html.append(head,body); //Instead of `.appendChild()` for each node.
document.documentElement.replaceWith(html); //“Only one element on document allowed.”
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.