使用Chrome扩展程序

时间:2016-09-04 13:41:42

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

我正在开发一个Chrome扩展程序,用于对Google搜索结果进行文本解析。我希望用户在多功能框中插入某个文字,然后直接转到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');

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

1 个答案:

答案 0 :(得分:2)

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

您的代码在导航到页面和处理Web导航的异步特性方面存在问题。这也不是您提出的问题,但会影响您对网页上的文字提出的要求。

因此,为了回答您如何从网页中提取纯文本的问题,我在用户点击browser_action按钮时实现了这一点。这就分开了如何解决代码中其他问题的问题。

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