obtain mouse coordinates through chrome extension

后端 未结 4 1592
夕颜
夕颜 2021-02-06 11:22

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

4条回答
  •  太阳男子
    2021-02-06 11:58

    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 + ")")
    };
    

提交回复
热议问题