mirror of
https://github.com/puppeteer/puppeteer
synced 2024-06-14 14:02:48 +00:00
refactor: simplify EmulationManager (#2816)
EmualationManager used to be injecting touch hooks to properly support touch emulation. However, these are no longer necessary, since https://crbug.com/133915 is long fixed.
This commit is contained in:
parent
c4acc63775
commit
871b204fd1
@ -1,3 +1,4 @@
|
||||
test/assets/modernizr.js
|
||||
third_party/*
|
||||
utils/doclint/check_public_api/test/
|
||||
utils/testrunner/examples/
|
||||
|
@ -21,7 +21,7 @@ class EmulationManager {
|
||||
constructor(client) {
|
||||
this._client = client;
|
||||
this._emulatingMobile = false;
|
||||
this._injectedTouchScriptId = null;
|
||||
this._hasTouch = false;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -35,44 +35,19 @@ class EmulationManager {
|
||||
const deviceScaleFactor = viewport.deviceScaleFactor || 1;
|
||||
/** @type {Protocol.Emulation.ScreenOrientation} */
|
||||
const screenOrientation = viewport.isLandscape ? { angle: 90, type: 'landscapePrimary' } : { angle: 0, type: 'portraitPrimary' };
|
||||
const hasTouch = viewport.hasTouch || false;
|
||||
|
||||
await Promise.all([
|
||||
this._client.send('Emulation.setDeviceMetricsOverride', { mobile, width, height, deviceScaleFactor, screenOrientation }),
|
||||
this._client.send('Emulation.setTouchEmulationEnabled', {
|
||||
enabled: viewport.hasTouch || false
|
||||
enabled: hasTouch
|
||||
})
|
||||
]);
|
||||
|
||||
let reloadNeeded = false;
|
||||
if (viewport.hasTouch && !this._injectedTouchScriptId) {
|
||||
const source = `(${injectedTouchEventsFunction})()`;
|
||||
this._injectedTouchScriptId = (await this._client.send('Page.addScriptToEvaluateOnNewDocument', { source })).identifier;
|
||||
reloadNeeded = true;
|
||||
} else if (!viewport.hasTouch && this._injectedTouchScriptId) {
|
||||
await this._client.send('Page.removeScriptToEvaluateOnNewDocument', {identifier: this._injectedTouchScriptId});
|
||||
this._injectedTouchScriptId = null;
|
||||
reloadNeeded = true;
|
||||
}
|
||||
|
||||
if (this._emulatingMobile !== mobile)
|
||||
reloadNeeded = true;
|
||||
const reloadNeeded = this._emulatingMobile !== mobile || this._hasTouch !== hasTouch;
|
||||
this._emulatingMobile = mobile;
|
||||
this._hasTouch = hasTouch;
|
||||
return reloadNeeded;
|
||||
|
||||
function injectedTouchEventsFunction() {
|
||||
const touchEvents = ['ontouchstart', 'ontouchend', 'ontouchmove', 'ontouchcancel'];
|
||||
// @ts-ignore
|
||||
const recipients = [window.__proto__, document.__proto__];
|
||||
for (let i = 0; i < touchEvents.length; ++i) {
|
||||
for (let j = 0; j < recipients.length; ++j) {
|
||||
if (!(touchEvents[i] in recipients[j])) {
|
||||
Object.defineProperty(recipients[j], touchEvents[i], {
|
||||
value: null, writable: true, configurable: true, enumerable: true
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -2,15 +2,11 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>Detect Touch Test</title>
|
||||
<script>
|
||||
/*! modernizr 3.5.0 (Custom Build) | MIT *
|
||||
* https://modernizr.com/download/?-touchevents-setclasses !*/
|
||||
!function(e,n,t){function o(e,n){return typeof e===n}function s(){var e,n,t,s,a,i,r;for(var l in c)if(c.hasOwnProperty(l)){if(e=[],n=c[l],n.name&&(e.push(n.name.toLowerCase()),n.options&&n.options.aliases&&n.options.aliases.length))for(t=0;t<n.options.aliases.length;t++)e.push(n.options.aliases[t].toLowerCase());for(s=o(n.fn,"function")?n.fn():n.fn,a=0;a<e.length;a++)i=e[a],r=i.split("."),1===r.length?Modernizr[r[0]]=s:(!Modernizr[r[0]]||Modernizr[r[0]]instanceof Boolean||(Modernizr[r[0]]=new Boolean(Modernizr[r[0]])),Modernizr[r[0]][r[1]]=s),f.push((s?"":"no-")+r.join("-"))}}function a(e){var n=u.className,t=Modernizr._config.classPrefix||"";if(p&&(n=n.baseVal),Modernizr._config.enableJSClass){var o=new RegExp("(^|\\s)"+t+"no-js(\\s|$)");n=n.replace(o,"$1"+t+"js$2")}Modernizr._config.enableClasses&&(n+=" "+t+e.join(" "+t),p?u.className.baseVal=n:u.className=n)}function i(){return"function"!=typeof n.createElement?n.createElement(arguments[0]):p?n.createElementNS.call(n,"http://www.w3.org/2000/svg",arguments[0]):n.createElement.apply(n,arguments)}function r(){var e=n.body;return e||(e=i(p?"svg":"body"),e.fake=!0),e}function l(e,t,o,s){var a,l,f,c,d="modernizr",p=i("div"),h=r();if(parseInt(o,10))for(;o--;)f=i("div"),f.id=s?s[o]:d+(o+1),p.appendChild(f);return a=i("style"),a.type="text/css",a.id="s"+d,(h.fake?h:p).appendChild(a),h.appendChild(p),a.styleSheet?a.styleSheet.cssText=e:a.appendChild(n.createTextNode(e)),p.id=d,h.fake&&(h.style.background="",h.style.overflow="hidden",c=u.style.overflow,u.style.overflow="hidden",u.appendChild(h)),l=t(p,e),h.fake?(h.parentNode.removeChild(h),u.style.overflow=c,u.offsetHeight):p.parentNode.removeChild(p),!!l}var f=[],c=[],d={_version:"3.5.0",_config:{classPrefix:"",enableClasses:!0,enableJSClass:!0,usePrefixes:!0},_q:[],on:function(e,n){var t=this;setTimeout(function(){n(t[e])},0)},addTest:function(e,n,t){c.push({name:e,fn:n,options:t})},addAsyncTest:function(e){c.push({name:null,fn:e})}},Modernizr=function(){};Modernizr.prototype=d,Modernizr=new Modernizr;var u=n.documentElement,p="svg"===u.nodeName.toLowerCase(),h=d._config.usePrefixes?" -webkit- -moz- -o- -ms- ".split(" "):["",""];d._prefixes=h;var m=d.testStyles=l;Modernizr.addTest("touchevents",function(){var t;if("ontouchstart"in e||e.DocumentTouch&&n instanceof DocumentTouch)t=!0;else{var o=["@media (",h.join("touch-enabled),("),"heartz",")","{#modernizr{top:9px;position:absolute}}"].join("");m(o,function(e){t=9===e.offsetTop})}return t}),s(),a(f),delete d.addTest,delete d.addAsyncTest;for(var v=0;v<Modernizr._q.length;v++)Modernizr._q[v]();e.Modernizr=Modernizr}(window,document);
|
||||
</script>
|
||||
<script src='modernizr.js'></script>
|
||||
</head>
|
||||
<body style="font-size:30vmin">
|
||||
<script>
|
||||
document.body.textContent = Modernizr.touchevents ? 'YES' : 'NO';
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
</html>
|
||||
|
3
test/assets/modernizr.js
Normal file
3
test/assets/modernizr.js
Normal file
@ -0,0 +1,3 @@
|
||||
/*! modernizr 3.5.0 (Custom Build) | MIT *
|
||||
* https://modernizr.com/download/?-touchevents-setclasses !*/
|
||||
!function(e,n,t){function o(e,n){return typeof e===n}function s(){var e,n,t,s,a,i,r;for(var l in c)if(c.hasOwnProperty(l)){if(e=[],n=c[l],n.name&&(e.push(n.name.toLowerCase()),n.options&&n.options.aliases&&n.options.aliases.length))for(t=0;t<n.options.aliases.length;t++)e.push(n.options.aliases[t].toLowerCase());for(s=o(n.fn,"function")?n.fn():n.fn,a=0;a<e.length;a++)i=e[a],r=i.split("."),1===r.length?Modernizr[r[0]]=s:(!Modernizr[r[0]]||Modernizr[r[0]]instanceof Boolean||(Modernizr[r[0]]=new Boolean(Modernizr[r[0]])),Modernizr[r[0]][r[1]]=s),f.push((s?"":"no-")+r.join("-"))}}function a(e){var n=u.className,t=Modernizr._config.classPrefix||"";if(p&&(n=n.baseVal),Modernizr._config.enableJSClass){var o=new RegExp("(^|\\s)"+t+"no-js(\\s|$)");n=n.replace(o,"$1"+t+"js$2")}Modernizr._config.enableClasses&&(n+=" "+t+e.join(" "+t),p?u.className.baseVal=n:u.className=n)}function i(){return"function"!=typeof n.createElement?n.createElement(arguments[0]):p?n.createElementNS.call(n,"http://www.w3.org/2000/svg",arguments[0]):n.createElement.apply(n,arguments)}function r(){var e=n.body;return e||(e=i(p?"svg":"body"),e.fake=!0),e}function l(e,t,o,s){var a,l,f,c,d="modernizr",p=i("div"),h=r();if(parseInt(o,10))for(;o--;)f=i("div"),f.id=s?s[o]:d+(o+1),p.appendChild(f);return a=i("style"),a.type="text/css",a.id="s"+d,(h.fake?h:p).appendChild(a),h.appendChild(p),a.styleSheet?a.styleSheet.cssText=e:a.appendChild(n.createTextNode(e)),p.id=d,h.fake&&(h.style.background="",h.style.overflow="hidden",c=u.style.overflow,u.style.overflow="hidden",u.appendChild(h)),l=t(p,e),h.fake?(h.parentNode.removeChild(h),u.style.overflow=c,u.offsetHeight):p.parentNode.removeChild(p),!!l}var f=[],c=[],d={_version:"3.5.0",_config:{classPrefix:"",enableClasses:!0,enableJSClass:!0,usePrefixes:!0},_q:[],on:function(e,n){var t=this;setTimeout(function(){n(t[e])},0)},addTest:function(e,n,t){c.push({name:e,fn:n,options:t})},addAsyncTest:function(e){c.push({name:null,fn:e})}},Modernizr=function(){};Modernizr.prototype=d,Modernizr=new Modernizr;var u=n.documentElement,p="svg"===u.nodeName.toLowerCase(),h=d._config.usePrefixes?" -webkit- -moz- -o- -ms- ".split(" "):["",""];d._prefixes=h;var m=d.testStyles=l;Modernizr.addTest("touchevents",function(){var t;if("ontouchstart"in e||e.DocumentTouch&&n instanceof DocumentTouch)t=!0;else{var o=["@media (",h.join("touch-enabled),("),"heartz",")","{#modernizr{top:9px;position:absolute}}"].join("");m(o,function(e){t=9===e.offsetTop})}return t}),s(),a(f),delete d.addTest,delete d.addAsyncTest;for(var v=0;v<Modernizr._q.length;v++)Modernizr._q[v]();e.Modernizr=Modernizr}(window,document);
|
@ -1276,6 +1276,11 @@ module.exports.addTests = function({testRunner, expect, puppeteer, DeviceDescrip
|
||||
await page.goto(server.PREFIX + '/detect-touch.html');
|
||||
expect(await page.evaluate(() => document.body.textContent.trim())).toBe('YES');
|
||||
});
|
||||
it('should detect touch when applying viewport with touches', async({page, server}) => {
|
||||
await page.setViewport({ width: 800, height: 600, hasTouch: true });
|
||||
await page.addScriptTag({url: server.PREFIX + '/modernizr.js'});
|
||||
expect(await page.evaluate(() => Modernizr.touchevents)).toBe(true);
|
||||
});
|
||||
it('should support landscape emulation', async({page, server}) => {
|
||||
await page.goto(server.PREFIX + '/mobile.html');
|
||||
expect(await page.evaluate(() => screen.orientation.type)).toBe('portrait-primary');
|
||||
|
Loading…
Reference in New Issue
Block a user