2017-01-05 3 views
-1

私は時折、svg文書をHTML文書に変換する必要があるという私的な拡張を持っています。私は、ページがbody要素が含まれていないこととlocation.hrefは「.SVG」のテキストが含まれていることを検出した場合空のSVG文書からHTMLページを作成する正しい方法

は私が動作しているよう

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); 

次してみてください(文書がSVG文書です) 。ページを検査する標準文書

<html> 
    <head></head> 
    <body></body> 
</html> 

を示ししかし、私はアクセスdocument.body.styleにしようとしたとき、私はヌルreferanceエラーを取得します。 document.bodyは、私はその後、

// leading on from first snippet 
document.body = body; // line 8712 

と直接document.body要素を設定しようと、私は、私はちょうど空のドキュメントから使用可能なHTMLドキュメントを作成することができないようUncaught TypeError: Failed to set the 'body' property on 'Document': The provided value is not of type 'HTMLElement'. at contentscript.js:8712

を得るに十分なフェアnullに等しいです。 可能ですか?

リダイレクトすると、ドメインと関連付けられたセッションが削除されるため、ページが本当に必要です。

+0

ドキュメントを完全に消去して新しいドキュメントを作成する必要がありますか、または単に「ボディ」の新しいコンテンツを作成することはできますか? –

+0

@ScottMarcus私はSVGコンテンツを取り除く必要があります。それはページが ''として始まり、すべてが含まれています – Blindman67

+1

@ aw04あなたはsvg文書から始めましたか?つまり、アドレスバーには「http://someDomain.com/someImage.svg」のようなものがあります。 – Blindman67

答えて

2

正しい名前空間内の要素を入れて

<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> 

を使用して参照してくださいhttp://alohci.net/static/Blindman67_1.svg

SVGドキュメント(つまりXHTML以外のXMLドキュメント)のdocument.createElement()は、HTML名前空間で必要に応じてnull名前空間に要素を作成します。

+0

うん、名前空間が問題だった。私は新しいDOMを書くことができましたが、HTMLを解析することができませんでした。 '.removeChild()'と '' fyi''の代わりに '.replaceChild()'を使うこともできます。var newDoctype = document.implementation.createDocumentType( 'html'、 ''、 ')で新しい 'DOCTYPE'を作成することができます。 '); document.insertBefore(newDoctype、document.childNodes [0]); '、それを処理するためにドキュメントを再ロードする必要があるので、それは何もしません。 –

+0

ありがとう、私は動作しているHTMLDocumentを持っていますが、今は 'document.createElementNS(" http://www.w3.org/1999/xhtml "、elementType)ですべての要素を作成する必要があります。スタイルアトリビュート。2つのlibsと10K行のコードがあるので、リファクタリングではなく、私自身の関数を 'document.createElement'に割り当てますが、スタイル属性がないために使用している別の拡張が失敗します。迅速な解決策はありますか?そうでない場合は、別の時間に質問として投稿してください。 – Blindman67

関連する問題