我拼命寻找在单击上下文菜单或使用快捷键时检索用户鼠标坐标的方法
如果可能的话,我希望不必使用需要用户移动的 onmousemove 事件:/
你知道怎么做吗?
提前感谢您的回复
最佳答案
这只是一个简单的示例,仅适用于:
文件
-> 更改 manifest.json 中的 "matches": ["file:"] 以添加新功能
上下文菜单选择
-> 更改上下文:contextMenus.create (bg.js) 中的 ["selection"] 以添加新功能
辅助鼠标按钮
-> 在 (c.js) 中更改 (mousePos.button == 2) 以添加新功能
你也可以试试 mousedown 事件
为了运行和测试,创建这三个文件,在 chrome 中加载扩展程序,在 chrome 中加载任何文件(example.txt),选择任何文本,然后(辅助鼠标按钮单击)出现新的上下文菜单。只需单击即可获取光标位置。
测试和工作:2014 年 3 月 26 日 在 chrome 版本 33.0.1750.154 上
欢迎任何意见;)
list .json
{
"name": "menuContext position",
"version": "0.1",
"description": "determine menuContext position",
"permissions": ["contextMenus"],
"content_security_policy": "script-src 'self'; object-src 'self'",
"background": {
"scripts": ["bg.js"]
},
"content_scripts": [{
"matches": ["file:///*/*"],
"js": ["c.js"],
"run_at": "document_end",
"all_frames": true
}],
"manifest_version": 2
}
c.js
'use strict';
// when mouse up, send message to background.js with this position
document.addEventListener('mouseup', function (mousePos) {
if (mousePos.button == 2) {
var p = {clientX: mousePos.clientX, clientY: mousePos.clientY};
var msg = {text: 'example', point: p, from: 'mouseup'};
chrome.runtime.sendMessage(msg, function(response) {});
}
})
bg.js
'use strict';
//global var for store cursor position
var gPos = null;
//receiving message
chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.from == 'mouseup') {
//storing position
gPos = msg.point;
}
})
// onclick callback function.
function OnClick(info, tab, text, mousePos) {
if (info.menuItemId == idConsole) {
if (gPos != null) {
alert('Position X: ' + gPos.clientX + '\nPosition Y: ' + gPos.clientY );
//console.log('Position X: ' + gPos.clientX + '\nPosition Y: ' + gPos.clientY );
}
}
}
//on click sample callback with more params
var idConsole = chrome.contextMenus.create({
title: 'Cursor Position',
contexts: ["selection"],
onclick: function(info, tab) {
OnClick(info, tab, '%s', gPos);
}
})
如果可能,请在您的问题中添加标签 [google-chrome-extension]。问候
关于javascript - 在谷歌浏览器扩展中获取鼠标坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22278159/