2012-09-14 3 views
2

선택한 텍스트를 가져 와서 Google에서 검색하는 확장 프로그램을 만들고 싶습니다. 번역은 이지만 선택한 텍스트를 가져 오는 방법을 알 수는 없습니다. 여기 크롬 확장에서 선택된 텍스트 가져 오기

내 manifest.json을

{ 
"manifest_version": 2, 
"name": "Saeed Translate", 
"version": "1", 
"description": "Saeed Translate for Chrome", 
"icons": { 
    "16": "icon.png" 
    }, 
"content_scripts": [ { 
     "all_frames": true, 
     "js": [ "content_script.js" ], 
     "matches": [ "http://*/*", "https://*/*" ], 
     "run_at": "document_start" 
    } ], 
"background": { 
    "scripts": ["background.js"] 
    }, 
"permissions": [ 
"contextMenus", 
"background", 
"tabs" 
] 

} 

하고 내 background.js는

var text = "http://translate.google.com/#auto/fa/"; 
function onRequest(request, sender, sendResponse) { 
    text = "http://translate.google.com/#auto/fa/"; 
    text = text + request.action.toString(); 

sendResponse({}); 
}; 

chrome.extension.onRequest.addListener(onRequest); 
chrome.contextMenus.onClicked.addListener(function(tab) { 
    chrome.tabs.create({url:text}); 
}); 
chrome.contextMenus.create({title:"Translate '%s'",contexts: ["selection"]}); 

파일 내 content_script.js이 파일

var sel = window.getSelection(); 
var selectedText = sel.toString(); 
chrome.extension.sendRequest({action: selectedText}, function(response) { 
    console.log('Start action sent'); 
}); 

내가 선택한 텍스트를 얻는 방법 ?

+0

실제로 보내지는 항목은 무엇입니까? 오류 메시지가 있습니까? 작동하지 않는 것에 대한 세부 정보를 제공하지 않으면 알기가 어렵습니다. –

+0

문서를 읽으십시오. 특히 selectionText 속성은 http://developer.chrome.com/extensions/contextMenus.html#type-OnClickData –

+0

입니다. content_script.js의 selectedText는 실제로 비어 있습니다. –

답변

7

정말 복잡한 것입니다. contextMenus.create 메서드가 이미 선택된 텍스트를 캡처 할 수 있기 때문에 내용 스크립트와 배경 페이지간에 메시지를 사용할 필요가 없습니다. 원격 구글과 같은 외부 사이트 당신이 번역에 액세스하려면

function onRequest(info, tab) { 
var selection = info.selectionText; 
//do something with the selection 
}; 

참고 : 단순히 info.selectionText을 얻기 위해 그런 다음 기능을 조정

chrome.contextMenus.create({title:"Translate '%s'",contexts: ["all"], "onclick": onRequest}); 

:처럼 뭔가에 작품 스크립트를 조정합니다 권한 설정을 조정해야 할 수도 있습니다.

관련 문제