0

When I select text in the browser and click the context menu I want to get HTML content from the selected text

Here is my code,

chrome.contextMenus.onClicked.addListener(function(info, tab) {
    if (info.menuItemId === "menu1") {
        var html = getSelectionHtml();
    }
});

I have tried this function but its uses for web

function getSelectionHtml() {
    var html = "";
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var container = document.createElement("div");
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                container.appendChild(sel.getRangeAt(i).cloneContents());
            }
            html = container.innerHTML;
        }
    } else if (typeof document.selection != "undefined") {
        if (document.selection.type == "Text") {
            html = document.selection.createRange().htmlText;
        }
    }
    return html;
}
Mitesh Rathod
  • 879
  • 5
  • 18
  • Does this answer your question? [How to access the webpage DOM rather than the extension page DOM?](https://stackoverflow.com/questions/4532236/how-to-access-the-webpage-dom-rather-than-the-extension-page-dom) – wOxxOm Mar 14 '20 at 14:52
  • Thanks @wOxxOm, but What I need to do. let me give you an example: I want to get some selects content from the page. so When I select the content I want that selected content HTML. in string format the out would be like this ```'

    Hello World

    Welcome
    '```
    – Mitesh Rathod Mar 14 '20 at 15:03
  • See the linked answer and run your code as shown there. – wOxxOm Mar 14 '20 at 15:17

0 Answers0