Is there a way to tell Chrome web debugger to show the current mouse position in page coordinates?
You could type this into the console,
document.onmousemove = function(e){
var x = e.pageX;
var y = e.pageY;
e.target.title = "X is "+x+" and Y is "+y;
};
This will give you mouse position on mouse move in the element tooltip.
How do I view the x and y position of an element through Chrome DevTools?
You could type this into the console,
document.onmousemove = function(e){
var x = e.pageX;
var y = e.pageY;
e.target.title = "X is "+x+" and Y is "+y;
};
This will give you mouse position on mouse move in the element tooltip.
obtain mouse coordinates through chrome extension
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 + ")")
};
How to get cursor position in a Chrome DevTools source editor from extension?
This has been explained as per reported Chrome Issue 747888:
So first of all,
setOpenResourceHandle()
is for the cases when users click a link (e.g. alinkified
location in console) that normally results in opening a source tab in DevTools, it's not meant to be fired when a file is explicitly opened in the source panel. For changes of the file/position within the sources tab, we've gotchrome.devtools.panels.sources.onSelectionChanged
(see a layout test for example usage) that was recently brought back by @jacobr).
Here is the mentioned code example:
function extension_testElementsOnSelectionChanged(nextTest)
{
function onSelectionChanged()
{
webInspector.panels.elements.onSelectionChanged.removeListener(onSelectionChanged);
output("onSelectionChanged fired");
nextTest();
}
webInspector.panels.elements.onSelectionChanged.addListener(onSelectionChanged);
webInspector.inspectedWindow.eval("inspect(document.body.children[0]), 0");
}
function extension_testSourcesOnSelectionChangedShowFile(nextTest)
{
function onSelectionChanged(selectionInfo)
{
webInspector.panels.sources.onSelectionChanged.removeListener(onSelectionChanged);
output("sources onSelectionChanged fired, selectionInfo:");
dumpObject(selectionInfo, {url: "url"});
nextTest();
}
webInspector.panels.sources.onSelectionChanged.addListener(onSelectionChanged);
evaluateOnFrontend("InspectorTest.showScriptSource(\"test-script.js\")");
}
function extension_testSourcesOnSelectionChangedShowFileAndLine(nextTest)
{
webInspector.inspectedWindow.eval("location.href", function(inspectedPageURL) {
function onSelectionChanged(selectionInfo)
{
webInspector.panels.sources.onSelectionChanged.removeListener(onSelectionChanged);
output("sources onSelectionChanged fired, selectionInfo:");
dumpObject(selectionInfo, {url: "url"});
nextTest();
}
webInspector.panels.sources.onSelectionChanged.addListener(onSelectionChanged);
var basePath = inspectedPageURL.replace(/\/[^/]*$/, "/");
webInspector.panels.openResource(basePath + "resources/test-script.js", 2);
});
}
How to get the mouse position without events (without moving the mouse)?
Real answer: No, it's not possible.
OK, I have just thought of a way. Overlay your page with a div that covers the whole document. Inside that, create (say) 2,000 x 2,000 <a>
elements (so that the :hover
pseudo-class will work in IE 6, see), each 1 pixel in size. Create a CSS :hover
rule for those <a>
elements that changes a property (let's say font-family
). In your load handler, cycle through each of the 4 million <a>
elements, checking currentStyle
/ getComputedStyle()
until you find the one with the hover font. Extrapolate back from this element to get the co-ordinates within the document.
N.B. DON'T DO THIS.
How do I get the coordinates of a mouse click on a canvas element?
If you like simplicity but still want cross-browser functionality I found this solution worked best for me. This is a simplification of @Aldekein´s solution but without jQuery.
function getCursorPosition(canvas, event) {
const rect = canvas.getBoundingClientRect()
const x = event.clientX - rect.left
const y = event.clientY - rect.top
console.log("x: " + x + " y: " + y)
}
const canvas = document.querySelector('canvas')
canvas.addEventListener('mousedown', function(e) {
getCursorPosition(canvas, e)
})
React, Want to get current mouse position of the current element
I made you a pen using e.clientX - e.target.offsetLeft
and e.clientY - e.target.offsetTop
. The top left corner of the canvas (in pink) is giving me 0,0 which seems right.
get mouse coordinate in google chrome extension
This is just a simple sample, and only works with:
files
-> change "matches": ["file:"] in manifest.json to add new capabilities
context menu selection
-> change contexts: ["selection"] in contextMenus.create (bg.js) to add new capabilities
secondary mouse button
-> change (mousePos.button == 2) in (c.js) to add new capabilities
You can try also with mousedown event
For run and test, create these three files, load the extension in chrome, load any file in chrome (example.txt), select any text and then, (secondary mouse button click) new context menu appears. Just click for get Cursor Position.
Tested and working: 26 march 2014 on chrome Versión 33.0.1750.154
Any comments are welcome ;)
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);
}
})
Please, if possible, add tag [google-chrome-extension] to your question. Greetings
Find mouse position relative to element
For people using JQuery:
Sometimes, when you have nested elements, one of them with the event attached to it, it can be confusing to understand what your browser sees as the parent. Here, you can specify which parent.
You take the mouse position, and then subtract it from the parent element's offset position.
var x = evt.pageX - $('#element').offset().left;
var y = evt.pageY - $('#element').offset().top;
If you're trying to get the mouse position on a page inside a scrolling pane:
var x = (evt.pageX - $('#element').offset().left) + self.frame.scrollLeft();
var y = (evt.pageY - $('#element').offset().top) + self.frame.scrollTop();
Or the position relative to the page:
var x = (evt.pageX - $('#element').offset().left) + $(window).scrollLeft();
var y = (evt.pageY - $('#element').offset().top) + $(window).scrollTop();
Note the following performance optimisation:
var offset = $('#element').offset();
// Then refer to
var x = evt.pageX - offset.left;
In this way, JQuery does not have to look up #element
for each line.
There is a newer, JavaScript-only version in an answer by @anytimecoder -- see also browser support for getBoundingClientRect().
How can I check the pixel location of my cursor?
Use javascript to get cursor location.
document.addEventListener("mouseover", function( event ) {
console.log(event.screenX, event.screenY);
}, false);
Related Topics
How to Sort Elements in an Array into Order and Even Numbers and They Should Be in Ascending Order
How to Use Zindex in React-Native
How to Show a Confirmation Dialog Box in Toastr
How to Reduce Vendor/Script Bundle.Js in Angular 5
React Hooks Error: Hooks Can Only Be Called Inside the Body of a Function Component
How to Assign Empty Value to Select Dropdown
How to Check a Postal Code in JavaScript
Firebase.Firestore() Is Not a Function When Trying to Initialize Cloud Firestore
How to Make a Triangle Using for Loop JavaScript
Disable Right-Clicking in Html5 Video
Reverse Strings Without Changing the Order of Words in a Sentence
Uncheck a Checkbox and Another Checkbox Will Untick
How to Close Sweet Alert on Ajax Request Completion
How to Wait Until 2 $Http Requests End in Angularjs
How to Show an Alert After Reloading the Page in JavaScript
How to Redirect to Another Page in Reactjs When a If Condition Is Executed