完全なライブ HTML ドキュメントをシリアル化するには、次のコードを使用します。
// @author Rob W <http://stackoverflow.com/users/938089/rob-w>
// Demo: var serialized_html = DOMtoString(document);
function DOMtoString(document_root) {
var html = '',
node = document_root.firstChild;
while (node) {
switch (node.nodeType) {
case Node.ELEMENT_NODE:
html += node.outerHTML;
break;
case Node.TEXT_NODE:
html += node.nodeValue;
break;
case Node.CDATA_SECTION_NODE:
html += '<![CDATA[' + node.nodeValue + ']]>';
break;
case Node.COMMENT_NODE:
html += '<!--' + node.nodeValue + '-->';
break;
case Node.DOCUMENT_TYPE_NODE:
// (X)HTML documents are identified by public identifiers
html += "<!DOCTYPE "
+ node.name
+ (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '')
+ (!node.publicId && node.systemId ? ' SYSTEM' : '')
+ (node.systemId ? ' "' + node.systemId + '"' : '')
+ '>\n';
break;
}
node = node.nextSibling;
}
return html;
}
ここで、Chrome 拡張機能では、バックグラウンド ページやポップアップ ページなどの拡張機能ページにいくつかのイベントを追加する必要があります。
/**
* Get the HTML source for the main frame of a given tab.
*
* @param {integer} tabId - ID of tab.
* @param {function} callback - Called with the tab's source upon completion.
*/
function getSourceFromTab(tabId, callback) {
// Capture the page when it has fully loaded.
// When we know the tab, execute the content script
chrome.tabs.onUpdated.addListener(onUpdated);
chrome.tabs.onRemoved.addListener(onRemoved);
function onUpdated(updatedTabId, details) {
if (details.status == 'complete') {
removeListeners();
chrome.tabs.executeScript(tabId, {
file: 'get_source.js'
}, function(results) {
// TODO: Detect injection error using chrome.runtime.lastError
var source = results[0];
done(source);
});
}
}
function removeListeners() {
chrome.tabs.onUpdated.removeListener(onUpdated);
chrome.tabs.onRemoved.removeListener(onRemoved);
}
function onRemoved() {
removeListeners();
callback(''); // Tab closed, no response.
}
}
上記の関数は、メイン フレームのソース コードをタブで返します。子フレームのソースを取得したい場合はchrome.tabs.executeScript
、frameId
パラメータで呼び出します。
次のスニペットは、拡張機能で関数を使用する方法の例を示しています。スニペットをバックグラウンド ページの consoleに貼り付けるか、 browserActionを宣言して、スニペットをonClicked
リスナーに配置し、拡張ボタンをクリックします。
var mypage = 'https://example.com';
var callback = function(html_string) {
console.log('HTML string, from extension: ', html_string);
};
chrome.tabs.create({
url: mypage
}, function(tab) {
getSourceFromTab(tab.id, callback);
});
参照get_source.js
されているには、次のコードが含まれています。
function DOMtoString(document_root) {
... see top of the answer...
}
// The value of the last expression of the content script is passed
// to the chrome.tabs.executeScript callback
DOMtoString(document);
ページから DOM を読み取ることができるように、適切なホスト権限を追加することを忘れないでください。"https://example.com/*"
上記の例では、manifest.json の "permissions" セクションに追加する必要があります。
関連ドキュメント