user782400 user782400 - 5 days ago 6
Javascript Question

obtain mouse coordinates through chrome extension

I am curious to know if there is a way to get the mouse coordinates through a chrome extension and then use these coordinates to check if the person has clicked in that position ?

Answer

Getting the mouse coordinates is very simple, put this in a content script:

document.onmousemove = function(e)
{
    var x = e.pageX;
    var y = e.pageY;
    // do what you want with x and y
};

Essentially, we are assigning a function to the onmousemove event of the entire page, and getting the mouse coordinates out of the event object (e).

However, I'm not entirely sure what you mean by this:

then use these coordinates to check if the person has clicked in that position ?

Do you want to check if a user clicks something like a button? In that case you can simply subscribe an event to that button (or any other element) like this:

document.getElementById("some_element").onclick = function(e)
{
    alert("User clicked button!");
};

To record all mouse clicks and where they are:

document.onclick = function(e)
{
    // e.target, e.srcElement and e.toElement contains the element clicked.
    alert("User clicked a " + e.target.nodeName + " element.");
};

Note that the mouse coordinates are still available in the event object (e).

If you need the coordinates when a user clicks an arbitrary location, this does the trick:

document.onclick = function(e)
{
    var x = e.pageX;
    var y = e.pageY;
    alert("User clicked at position (" + x + "," + y + ")")
};
Comments