2015-01-29 5 views
0

Я пытаюсь получить DOM, который я выбираю ContextMenu в Chrome Extension.Получить выбор DOM в chrome extension contextmenu

Код:

chrome.contextMenus.onClicked.addListener(function(info, tab){ 
    // the info.selectionText just the text, don not contains html. 
}); 

chrome.contextMenus.create({ 
    title: "Demo", 
    contexts: ["selection"], 
    id: "demo" 
}); 

но info.selectionText не содержит HTML DOM. Есть ли способ получить выборку в контексте расширения ChromeMenu ?. Пожалуйста, предложите. Благодарю.

+0

Возможный дубликат [Получить выбор страниц, включая HTML?] (Http://stackoverflow.com/questions/3461989/получить-страницу выбора, в том числе, HTML) –

ответ

3

Чтобы получить доступ к выбору, вам необходимо ввести content script на страницу.

Здесь вы можете позвонить getSelection(), чтобы получить Selection object и играть с диапазонами в нем, чтобы извлечь DOM, в котором вы нуждаетесь.

// "activeTab" permission is sufficient for this: 
chrome.contextMenus.onClicked.addListener(function(info, tab){ 
    chrome.tabs.executeScript(tab.id, {file: "getDOM.js"}) 
}); 

getDOM.js:

var selection = document.getSelection(); 
// extract the information you need 
// if needed, return it to the main script with messaging 

Вы можете взглянуть на Messaging docs.

0

Если вы хотите просто выбранный текст из контекстного меню, чем вы можете сделать это следующим кодом

function getClickHandler() { 
    return function(info, tab) { 
     // info.selectionText contain selected text when right clicking 
     console.log(info.selectionText); 
    }; 
    }; 


/** 
* Create a context menu which will only when text is selected. 
*/ 
chrome.contextMenus.create({ 
    "title" : "Get Text!", 
    "type" : "normal", 
    "contexts" : ["selection"], 
    "onclick" : getClickHandler() 
}); 
Смежные вопросы