【问题标题】:How to get html from current tab to popup如何从当前选项卡获取html到弹出窗口
【发布时间】:2013-10-28 11:46:25
【问题描述】:

我使用document.body.outerHTML 从标签中获取 html,但我做不到

ma​​nifest.json:

{
    "name": "SEO Analytic",
    "description": "Adds a print button to the browser.",
    "version": "1.2",
    "manifest_version": 2,

    "background": {
        "scripts": ["background.js"],
        "persistent": false
    },
    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js":      ["content.js"]
        }
    ],

    "permissions": ["tabs", "http://*/*", "https://*/*"],

    "browser_action": {
        "default_title": "SEO Analytic",
        "default_popup": "popup.html"
    }
}

popup.js:

chrome.tabs.getSelected(null, function(tab) {
    chrome.tabs.sendRequest(tab.id, {method: "getText"}, function(response) {
        if (response.method == "getText") {
            alltext = response.data;
            alert(alltext);
        }
    });
});

content.js:

chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
    if (request.method == "getText") {
        sendResponse({
            data: document.body.outerHTML,
            method: "getText"   // same as innerText
        });
    }
});

【问题讨论】:

  • 您尝试过我提出的解决方案吗?如果对你有用吗?

标签: google-chrome-extension


【解决方案1】:

似乎问题在于您使用了一些已弃用的功能。具体来说,使用您的代码,我在控制台日志中收到以下错误:

响应 tabs.getSelected 时出错:错误:sendRequest 和 onRequest 已过时。请改用 sendMessage 和 onMessage。

尽管可能仍然支持一些已弃用的东西,但它们肯定不会持续太久,因此迁移到最新的 API 和方法是个好主意。即:

有关如何将一些 HTML 内容从选项卡获取到弹出窗口(或背景页面)的详细答案,请参阅 my answer 相关问题。


顺便说一句,如果您不使用background.js,您可以从清单中完全删除“背景”键。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 2013-04-02
    • 1970-01-01
    • 2011-03-03
    相关资源
    最近更新 更多