在谷歌浏览器扩展程序中获取鼠标坐标

时间:2014-03-09 03:48:15

标签: javascript google-chrome google-chrome-extension mouse coordinate

当我点击我的contextMenu或使用shortcutKey

时,我拼命寻找检索用户鼠标坐标的方法

我希望尽可能不必使用需要移动用户的onmousemove事件:/

你知道吗?

提前感谢您的回复

1 个答案:

答案 0 :(得分:5)

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


文件     - >更改“匹配”: manifest.json 中的[“file:”]以添加新功能

上下文菜单选择     - >更改上下文: contextMenus.create(bg.js)中的[“selection”]以添加新功能

辅助鼠标按钮
    - >更改(c.js)中的(mousePos.button == 2)以添加新功能

您也可以尝试 mousedown 事件

对于运行和测试,创建这三个文件,在chrome中加载扩展,在chrome(example.txt)中加载任何文件,选择任何文本,然后,(鼠标左键单击)出现新的上下文菜单。只需单击即可获得光标位置。

经过测试和工作:2014年3月26日 onchromeVersión33.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]。问候