【问题标题】:Can I find the tag with selected text in a chrome extension?我可以在 chrome 扩展中找到带有选定文本的标签吗?
【发布时间】:2012-03-04 17:56:23
【问题描述】:
如果我在上下文菜单中添加了一项:
chrome.contextMenus.create({
"title" : chrome.i18n.getMessage("right_click") ,
"type" : "normal",
"contexts" : ["selection"],
"onclick" : my_function() // returns a callback function
});
如何获取包含所选内容的标签。
(我猜该选择是其innerHTML 的一部分)
编辑:
my_function 是一个工厂函数:它返回一个事件处理程序。
【问题讨论】:
标签:
javascript
google-chrome
text
google-chrome-extension
textselection
【解决方案1】:
您可以注入内容脚本并要求从脚本中进行选择。
content.js:
function getSel() {
//get text
var sel = window.getSelection().toString();
//or get parent tag for selection
//var sel = window.getSelection().getRangeAt(0).commonAncestorContainer;
if (sel) {
chrome.extension.sendRequest({
msg: 'data',
sel: sel
});
};
};
background.js:
var selText;
function onClickFunction(info, tab) {
chrome.tabs.executeScript(
tab.id,
{code: 'getSel()', allFrames: true},
function () {
//do anything with selText
}
);
};
chrome.extension.onRequest.addListener(function (request, sender, response) {
if (request.msg == 'data') {
selText = request.sel;
};
};