Chrome 扩展程序 - 确定上下文菜单中的选择文本或页面
Chrome Extension - Determining selection text or page in Context Menu
我目前正在尝试确定我的选择文本是否为 Null 或我的上下文是否 = ["页面"]。
目前我不确定如何编写正确的 if 和 else 语句来引用"上下文"和/或选择文本是否为空。 目前我已经编写了下面的代码,但是当单击菜单项时,这目前实际上并没有做任何事情。
chrome.contextMenus.onClicked.addListener(getword);
chrome.runtime.onInstalled.addListener(function() {
var contexts = ["page","selection","link","editable"];
var title = "Chrome Extension";
chrome.contextMenus.create({
"title": title,
"contexts": contexts,
"id": "main_parent"
});
});
function getword(info,tab) {
//Currently this simply checks for which menu item was clicked.
if (info.menuItemId == "main_parent") {
chrome.tabs.create({
url: "https://www.google.com/search?q=" + info.selectionText,
})
}
//Need to determine here if the context is a "page" and/or instead if info.selectionText is null, then do something... (Current Code below doesn't do anything)
if (info.selectionText == "") {
alert("PAGE is selected or Selection text is NULL");
}
如果您想知道上下文是否page
,您可以专门为页面上下文创建另一个上下文菜单:
chrome.contextMenus.onClicked.addListener(getword);
chrome.runtime.onInstalled.addListener(function() {
var contexts = ["selection","link","editable"];
var title = "Chrome Extension";
chrome.contextMenus.create({
"title": title,
"contexts": contexts,
"id": "context_for_all_but_page"
});
chrome.contextMenus.create({
"title": title,
"contexts": ["page"],
"id": "context_for_page"
});
});
这样,您可以区分两者:
function getword(info,tab)
{
if (typeof info.selectionText === "undefined")
alert("Selection text is undefined");
if (info.menuItemId === "context_for_page")
alert("PAGE is selected");
//Currently this simply checks for which menu item was clicked.
if (info.menuItemId === "context_for_all_but_page" && typeof info.selectionText !== "undefined") {
chrome.tabs.create({
url: "https://www.google.com/search?q=" + info.selectionText
});
}
}
请注意,我使用的是typeof info.selectionText === "undefined"
而不是info.selectionText == ""
。由于文档说它是 info
的可选参数,它将是未定义的而不是空字符串。
相关文章:
- 用于选择/文本框操作的JavaScript
- 以编程方式选择文本Mobile Safari
- Firefox输入可以't在选择文本时滚动
- 如何在javascript中取消选择文本框
- 如何在html中打印选择文本
- SVG元素——处理和选择文本
- 选择文本并添加到本地存储
- 选择“p文本jquery”
- 为什么火狐在我更改 innerHTML 时会选择文本
- 根据换行符选择文本
- 如何按从当前单词到段落中该句子(.)结尾的范围选择文本
- 单击按钮时选择文本
- JavaScript 触发器事件在 Android 上选择文本
- .val() 选择文本而不是值字符串,当网页动态编辑源 html
- 为什么不用特殊字符替换选择文本,以及如何删除此特殊字符
- 使用链接多次选择文本
- 使用jQuery在焦点上选择文本框是't在移动浏览器中工作
- Safari存在文本输入问题,用户输入时会选择文本,导致文本丢失
- Bootstrap下拉菜单-仅复选框不选择文本
- 使用.on的多个下拉菜单选择文本仅适用于第一个下拉菜单