2

chrome.tabs.create({'url': chrome.extension.getURL(mypage)}, function(tab) { /* ... */ }); Google Chrome拡張機能を開発していますが、新しいタブを開いて(わかりました、これは簡単です:) 、そのページのソースコードを取得する方法を知りたい です。

AJAXを使用してソースを取得できることは知っていますが、問題は、Webページにページを編集するJavascriptコードが含まれており、編集したページが必要なことです。

出来ますか?

4

1 に答える 1

9

完全なライブ 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.executeScriptframeIdパラメータで呼び出します。

次のスニペットは、拡張機能で関数を使用する方法の例を示しています。スニペットをバックグラウンド ページの 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" セクションに追加する必要があります。

関連ドキュメント

于 2012-04-15T13:06:52.533 に答える