Getting mouse coordinates in SDK first-time right-

2019-09-17 23:22发布

For an SDK add-on, I am trying to detect, on right-click, the closest page anchor (as described here).

Since JavaScript apparently has no way to query the mouse coordinates without first creating a mouse event listener, and since I don't want an expensive mouseover listener running all of the time on every single page! (and polling to rebuild a mouse listener is ugly and not fully accurate anyways), I was hoping I could get the mouse coordinates from a click event. Unfortunately, although self.on('click' does fire:

  1. This event is without an event object from which mouse coordinates could be obtained
  2. Adding a normal window.addEventListener('click',... listener doesn't actually get fired in the SDK content script with the first menu selection for some reason (it does fire subsequently, however).

Here is my workaround, but I want to fire on the current exact coordinates, not the coordinates of the node:

var x, y;
window.addEventListener('click', function (e) {
    if (e.button === 2) {
        x = e.clientX;
        y = e.clientY;
    }
}, true);

self.on('click', function (node) {
    if (!x) { // Since this is not showing the first time, we fire on the node (which is specifically an element, not a text node), though we really want the real clientX and clientY where the mouse is, not this simulation based on where the element is
        node.dispatchEvent(new MouseEvent('click', {
            button: 2
        }));
    }
    // Use document.caretPositionFromPoint with x and y to determine location of text

Is there any other way to get the actual mouse coordinates?

1条回答
走好不送
2楼-- · 2019-09-17 23:41

You can actually query the mouse coordinates without a mouse listener.

This page has a bunch of examples: https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes/Standard_OS_Libraries

It has to be done on per OS basis though as it uses JS-Ctypes. If you're worried about performance don't fear at all. You can use the code asynchronously via ChromeWorkers

查看更多
登录 后发表回答