获得鼠标坐标在谷歌chrome扩展

get mouse coordinate in google chrome extension

本文关键字:谷歌 chrome 扩展 坐标 鼠标      更新时间:2023-09-26

我拼命寻找方法来检索用户的鼠标坐标时,点击我的上下文菜单或使用快捷键

我想如果可能的话,不需要使用onmousemove事件,需要用户的移动:/

你知道怎么做吗?

提前感谢您的回复

这只是一个简单的示例,仅适用于:

文件


→更改清单中的matches": ["file:"]。Json 添加新功能

上下文菜单选择→change contexts: ["selection"] in contextMenus。创建(bg.js)添加新功能

鼠标次按键
(mousePos变化。Button == 2) in (c.js)添加新功能

你也可以试试mousedown event

对于运行和测试,创建这三个文件,在chrome中加载扩展,在chrome中加载任何文件(example.txt),选择任何文本,然后,(单击鼠标第二个按钮)出现新的上下文菜单。点击获取光标位置

测试并工作:2014年3月26日 chrome Versión 33.0.1750.154

欢迎任何评论;)

manifest.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]标签。问候