Skip to content

Commit dfed55c

Browse files
committed
Simplify emulation_manager
1 parent 34adb37 commit dfed55c

File tree

4 files changed

+17
-41
lines changed

4 files changed

+17
-41
lines changed

pyppeteer/emulation_manager.py

Lines changed: 7 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,9 @@ def __init__(self, client: CDPSession) -> None:
1414
"""Make new elmulation manager."""
1515
self._client = client
1616
self._emulatingMobile = False
17-
self._injectedTouchScriptId = None
17+
self._hasTouch = False
1818

19-
async def emulateViewport(self, viewport: dict
20-
) -> bool:
19+
async def emulateViewport(self, viewport: dict) -> bool:
2120
"""Evaluate viewport."""
2221
options = dict()
2322
mobile = viewport.get('isMobile', False)
@@ -34,45 +33,17 @@ async def emulateViewport(self, viewport: dict
3433
else:
3534
options['screenOrientation'] = {'angle': 0,
3635
'type': 'portraitPrimary'}
36+
hasTouch = viewport.get('hasTouch', False)
3737

3838
await self._client.send('Emulation.setDeviceMetricsOverride', options)
3939
await self._client.send('Emulation.setTouchEmulationEnabled', {
40-
'enabled': viewport.get('hasTouch', False),
40+
'enabled': hasTouch,
4141
'configuration': 'mobile' if mobile else 'desktop'
4242
})
4343

44-
injectedTouchEventsFunction = '''
45-
function injectedTouchEventsFunction() {
46-
const touchEvents = ['ontouchstart', 'ontouchend', 'ontouchmove', 'ontouchcancel'];
47-
const recepients = [window.__proto__, document.__proto__];
48-
for (let i = 0; i < touchEvents.length; ++i) {
49-
for (let j = 0; j < recepients.length; ++j) {
50-
if (!(touchEvents[i] in recepients[j])) {
51-
Object.defineProperty(recepients[j], touchEvents[i], {
52-
value: null, writable: true, configurable: true, enumerable: true
53-
});
54-
}
55-
}
56-
}
57-
}
58-
''' # noqa: E501
44+
reloadNeeded = (self._emulatingMobile != mobile or
45+
self._hasTouch != hasTouch)
5946

60-
reloadNeeded = False
61-
if viewport.get('hasTouch') and not self._injectedTouchScriptId:
62-
source = f'({injectedTouchEventsFunction})()'
63-
self._injectedTouchScriptId = (await self._client.send(
64-
'Page.addScriptToEvaluateOnNewDocument',
65-
{'source': source})).get('identifier')
66-
reloadNeeded = True
67-
elif not viewport.get('hasTouch') and self._injectedTouchScriptId:
68-
await self._client.send(
69-
'Page.removeScriptToEvaluateOnNewDocument',
70-
{'identifier': self._injectedTouchScriptId}
71-
)
72-
self._injectedTouchScriptId = None
73-
reloadNeeded = True
74-
75-
if self._emulatingMobile != mobile:
76-
reloadNeeded = True
7747
self._emulatingMobile = mobile
48+
self._hasTouch = hasTouch
7849
return reloadNeeded

tests/static/detect-touch.html

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,7 @@
22
<html>
33
<head>
44
<title>Detect Touch Test</title>
5-
<script>
6-
/*! modernizr 3.5.0 (Custom Build) | MIT *
7-
* https://modernizr.com/download/?-touchevents-setclasses !*/
8-
!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);
9-
</script>
5+
<script src="./modernizr.js"></script>
106
</head>
117
<body style="font-size:30vmin">
128
<script>

tests/static/modernizr.js

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

tests/test_page.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1270,6 +1270,12 @@ async def test_detect_by_modernizr(self):
12701270
'YES'
12711271
)
12721272

1273+
@sync
1274+
async def test_detect_touch_viewport_touch(self):
1275+
await self.page.setViewport({'width': 800, 'height': 600, 'hasTouch': True}) # noqa: E501
1276+
await self.page.addScriptTag({'url': self.url + 'static/modernizr.js'})
1277+
self.assertTrue(await self.page.evaluate('() => Modernizr.touchevents')) # noqa: E501
1278+
12731279
@sync
12741280
async def test_landscape_emulation(self):
12751281
await self.page.goto(self.url + 'static/mobile.html')

0 commit comments

Comments
 (0)