【问题标题】:Extract the whole text contained in webpage using Chrome extension使用 Chrome 扩展提取网页中包含的整个文本
【发布时间】:2017-01-12 01:17:47
【问题描述】:

我正在开发一个用于对 Google 搜索结果进行文本解析的 Chrome 扩展程序。我希望用户在多功能框中插入特定文本,然后直接进入 Google 搜索页面。

function navigate(url) {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { 
    chrome.tabs.update(tabs[0].id, {url: url});
    });
}

chrome.omnibox.onInputEntered.addListener(function(text) {
    navigate("https://www.google.com.br/search?hl=pt-BR&lr=lang_pt&q=" + text + "%20%2B%20cnpj");
});

alert('Here is where the text will be extracted');

将当前标签指向搜索页面后,我想获取页面的纯文本形式,然后进行解析。实现此目的最直接的方法是什么?

【问题讨论】:

标签: javascript google-chrome google-chrome-extension


【解决方案1】:

好吧,将网页解析为 DOM 而不是纯文本可能会更容易。但是,这不是您的问题。

您的代码在导航到页面的方式和处理网络导航的异步性质方面存在问题。这也不是您提出的问题,但会影响您提出的问题(从网页获取文本)的实现方式。

因此,为了回答您关于如何从网页中提取纯文本的问题,我在用户单击 browser_action 按钮时实现了这样做。这将回答如何做到这一点与代码中的其他问题分开。

正如wOxxOm 在评论中提到的,要访问网页的 DOM,您必须使用内容脚本。正如他所做的那样,我建议您阅读Overview of Chrome extensions。您可以使用chrome.tabs.executeScript 注入内容脚本。通常,您将使用details 参数的file 属性注入包含在单独文件中的脚本。对于只是发回网页文本的简单任务(无需解析等)的代码,只需插入最基本的方法所需的单行代码是合理的。要插入一小段代码,您可以使用details 参数的code 属性来执行此操作。在这种情况下,鉴于您没有说明您对文本的要求,document.body.innerText 是返回的文本。

要将文本发送回后台脚本,使用chrome.runtime.sendMessage()

为了接收后台脚本中的文本,将侦听器receiveText 添加到chrome.runtime.onMessage

background.js

chrome.browserAction.onClicked.addListener(function(tab) {
    console.log('Injecting content script(s)');
    //On Firefox document.body.textContent is probably more appropriate
    chrome.tabs.executeScript(tab.id,{
        code: 'document.body.innerText;'
        //If you had something somewhat more complex you can use an IIFE:
        //code: '(function (){return document.body.innerText})();'
        //If your code was complex, you should store it in a
        // separate .js file, which you inject with the file: property.
    },receiveText);
});

//tabs.executeScript() returns the results of the executed script
//  in an array of results, one entry per frame in which the script
//  was injected.
function receiveText(resultsArray){
    console.log(resultsArray[0]);
}

manifest.json

{
    "description": "Gets the text of a webpage and logs it to the console",
    "manifest_version": 2,
    "name": "Get Webpage Text",
    "version": "0.1",

    "permissions": [
        "activeTab"
    ],

    "background": {
        "scripts": [
            "background.js"
        ]
    },

    "browser_action": {
        "default_icon": {
            "32": "myIcon.png"
        },
        "default_title": "Get Webpage Text",
        "browser_style": true
    }
}

【讨论】:

    猜你喜欢
    • 2013-07-19
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多