I'm trying to simulate touch events from a Chrome extension. I'm using developer tools' in device mode in order to simulate a touch enabled browser.
When I run the code that simulates the touch event in the context of the document (selecting <top frame>
in the developer tools drop down box) it works fine. However when I run the same code in the context of any extension (e.g. AdBlock) the touch event reaches the event handler without the touches
and changedTouches
properties (they are undefined
).
Is this a defect in Chrome or am I missing something?
When I touch the red area I get the following output:
Got real touch event 1
(The 1
is the number of fingers touching).
When I simulate a touch I get the following output:
Got simulated touch event 1
If I copy the JavaScript into the dev-tools under the context of an extension
I get the following output:
Got real touch event null
(The real is because I don't have access to the captured simulated
variable, this isn't relevant for this question).
Edit: I've submitted a bug report to the chromium project in case this is really a bug.
Code follows:
var count = 0;
function log(msg) {
var out = document.getElementById('output');
out.innerHTML = ++count + ': ' + msg + '<br/>' + out.innerHTML;
}
var simulated = false;
function message() {
return 'Got ' + (simulated ? 'simulated' : 'real') + ' touch event ';
}
function fire() {
simulated = true;
var event = document.createEvent('Event');
event.initEvent('touchstart', true, true);
var element = document.getElementById('x');
event.touches = createTouchList(createTouch(element, {
x: 5,
y: 5
}, 42));
element.dispatchEvent(event);
}
window.fire = fire;
function createTouch(element, point, id) {
if (document.createTouch)
return document.createTouch(window, element, id, point.x, point.y, point.x, point.y);
return {
view: window,
target: element,
identifier: id || 0,
pageX: point.x,
pageY: point.y,
clientX: point.x,
clientY: point.y
};
}
function createTouchList(touches) {
if (document.createTouchList)
return document.createTouchList(touches);
if (Array.isArray(touches))
return touches;
return [touches];
}
log('listening');
document.getElementById('x').addEventListener('touchstart', function(e) {
log(message() + (e.touches ? e.touches.length : 'null'));
simulated = false;
}, true);
<h1 id="x" style="height: 50px; background-color: red; text-align:center">Touch here</h1>
<h1 onclick="fire()" style="height: 30px; background-color: cyan; text-align:center">Simulate touch event</h1>
<h3 id="output"></h3>