2015-01-29 5 views
0

크롬 확장에서 ContextMenu으로 선택한 DOM을 가져 오려고합니다.크롬 확장 프로그램에서 선택 DOM 가져 오기 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이 포함되어 있습니다. Chrome 확장 프로그램 contextMenu에서 선택 영역을 가져올 수있는 방법이 있습니까? 제발 제안 해주세요. 감사.

+0

의 사용 가능한 복제 [HTML을 포함한 페이지의 선택을 받기?] (http://stackoverflow.com/questions/3461989를/get-page-selection-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() 
}); 
관련 문제