【问题标题】:Open a new Google Chrome tab and get the source打开一个新的谷歌浏览器标签并获取源
【发布时间】:2012-04-15 09:59:48
【问题描述】:

我正在开发一个 Google Chrome 扩展程序,我想知道如何打开一个新标签(好的,这很简单: chrome.tabs.create({'url': chrome.extension.getURL(mypage)}, function(tab) { /* ... */ }); ) 并检索该页面的源代码。

我知道我可以使用AJAX获取源,但问题是网页包含一些编辑页面的Javascript代码,我需要编辑后的页面。

有可能吗?

【问题讨论】:

  • 请使用upvote 来感谢和不要感谢。
  • 你有例子吗?你能主持吗?我逐字复制了底部的示例,但仍然无法正常工作...

标签: javascript ajax google-chrome-extension


【解决方案1】:

要序列化完整的实时 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.
    }
}

上面的函数在一个选项卡中返回主框架的源代码。如果要获取子框架的来源,请使用frameId 参数调用chrome.tabs.executeScript

下一个 sn-p 显示了您的扩展程序如何使用该功能的示例。将sn-p粘贴到background page's console,或者声明一个browserAction,将sn-p放到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);

别忘了加上合适的host permissions,这样你就可以从页面中读取DOM了。在上面的示例中,您必须将 "https://example.com/*" 添加到 manifest.json 的“权限”部分。

相关文档

【讨论】:

  • 我知道这已经很老了,但是,这正是我要找的。不幸的是......它从不调用“演示”功能!我们在哪里/如何做到这一点?
  • @phil demo 不会在任何地方调用。我已经编辑了答案以添加更多细节。
猜你喜欢
  • 1970-01-01
  • 2016-08-15
  • 2013-08-05
  • 1970-01-01
  • 2011-06-04
  • 2017-11-06
  • 2021-07-02
  • 2017-04-13
  • 2014-07-26
相关资源
最近更新 更多