我試圖通過 DOMParser 將一個字符串解析為一個完整的 HTML 文檔,然后用處理過的節點覆蓋當前頁面。 該字符串包含完整的標記,包括<!doctype>
、 <html>
、 <head>
和<body>
節點。
// parse the string into a DOMDocument element:
var parser = new DOMParser();
var doc = parser.parseFromString(data, 'text/html');
// set the parsed head/body innerHTML contents into the current page's innerHTML
document.getElementsByTagName('head')[0].innerHTML = doc.getElementsByTagName('head')[0].innerHTML;
document.getElementsByTagName('body')[0].innerHTML = doc.getElementsByTagName('body')[0].innerHTML;
這是因為它成功地獲取了已解析的 HTML 節點並將它們呈現在頁面上; 但是,解析字符串內的<head>
或<body>
節點中存在的任何<script>
標記都無法執行 =[。 直接使用html
標簽(與head
/ body
相對)進行測試會產生相同的結果。
我也嘗試過使用.appendChild()
而不是.innerHTML()
,但沒有改變:
var elementHtml = document.getElementsByTagName('html')[0];
// remove the existing head/body nodes from the page
while (elementHtml.firstChild) elementHtml.removeChild(elementHtml.firstChild);
// append the parsed head/body tags to the existing html tag
elementHtml.appendChild(doc.getElementsByTagName('head')[0]);
elementHtml.appendChild(doc.getElementsByTagName('body')[0]);
有誰知道將字符串轉換為完整的 HTML 頁面並執行其中包含的 javascript 的方法嗎?
如果有替代 DOMParser 的方法可以提供相同的結果(例如覆蓋整個文檔),請隨時推薦它/它們 =]
注意:
我使用它而不是更簡單的document.write(data)
替代方案的原因是因為我需要在 SSL 下的 IE 中的postMessage()
回調中使用它; document.write()
在 IE 中訪問 SSL 頁面時在回調事件中被阻止,例如發布消息 =[