Chrome Extension - Get entire text content of the current tab

后端 未结 2 1669
别那么骄傲
别那么骄傲 2021-02-01 04:27

I\'m developing an extension where i need to get the entire text content on the current tab. Now i\'ve a plugin which retrieves selected text from the current tab. So, in essenc

2条回答
  •  盖世英雄少女心
    2021-02-01 04:42

    You can use document.body.innerText or document.all[0].innerText to do it in the content script.
    It will get all the text content in the page, without any HTML code.

    Or you can use document.all[0].outerHTML to get the HTML of the whole page.


    Example

    In the Content Script

    function getText(){
        return document.body.innerText
    }
    function getHTML(){
        return document.body.outerHTML
    }
    console.log(getText());             //Gives you all the text on the page
    console.log(getHTML());             //Gives you the whole HTML of the page
    

    Added

    So you want the content script to return the text to the popup. You can use:

    • chrome.tabs.getSelected to get the tab selected,
    • chrome.tabs.sendRequest to send request to the content script,
    • and chrome.extension.onRequest.addListener to listen to requests.

    Popup page

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

    Content Script

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

    This should work.

提交回复
热议问题