Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def _onTargetAttached(event: Dict) -> None:
targetInfo = event['targetInfo']
if targetInfo['type'] != 'worker':
# If we don't detach from service workers, they will never die.
try:
client.send('Target.detachFromTarget', {
'sessionId': event['sessionId'],
})
except Exception as e:
debugError(logger, e)
return
sessionId = event['sessionId']
session = client._createSession(targetInfo['type'], sessionId)
worker = Worker(
session,
targetInfo['url'],
self._addConsoleMessage,
self._handleException,
)
self._workers[sessionId] = worker
self.emit(Page.Events.WorkerCreated, worker)
deliverResult = '''
function deliverResult(name, seq, result) {
window[name]['callbacks'].get(seq)(result);
window[name]['callbacks'].delete(seq);
}
'''
expression = helper.evaluationString(deliverResult, name, seq, result)
try:
self._client.send('Runtime.evaluate', {
'expression': expression,
'contextId': event['executionContextId'],
})
except Exception as e:
helper.debugError(logger, e)
async def _clickablePoint(self) -> Dict[str, float]: # noqa: C901
result = None
try:
result = await self._client.send('DOM.getContentQuads', {
'objectId': self._remoteObject.get('objectId'),
})
except Exception as e:
debugError(logger, e)
if not result or not result.get('quads'):
raise ElementHandleError(
'Node is either not visible or not an HTMLElement')
quads = []
for _quad in result.get('quads'):
_q = self._fromProtocolQuad(_quad)
if _computeQuadArea(_q) > 1:
quads.append(_q)
if not quads:
raise ElementHandleError(
'Node is either not visible or not an HTMLElement')
quad = quads[0]
x = 0
async def killChrome(self) -> None:
"""Terminate chromium process."""
logger.info('terminate chrome process...')
if self.connection and self.connection._connected:
try:
await self.connection.send('Browser.close')
await self.connection.dispose()
except Exception as e:
# ignore errors on browser termination process
debugError(logger, e)
if self.temporaryUserDataDir and os.path.exists(self.temporaryUserDataDir): # noqa: E501
# Force kill chrome only when using temporary userDataDir
self.waitForChromeToClose()
self._cleanup_tmp_user_data_dir()
async def dispose(self) -> None:
"""Stop referencing the handle."""
if self._disposed:
return
self._disposed = True
try:
await helper.releaseObject(self._client, self._remoteObject)
except Exception as e:
debugError(logger, e)
executionContext = _execution_contexts[0]
return JSHandle(executionContext, client, remoteObject)
executionContext = ExecutionContext(
client, event['context'], jsHandleFactory)
_execution_contexts.append(executionContext)
self._executionContextCallback(executionContext)
self._client.on('Runtime.executionContextCreated',
onExecutionContentCreated)
try:
# This might fail if the target is closed before we recieve all
# execution contexts.
self._client.send('Runtime.enable', {})
except Exception as e:
debugError(logger, e)
def onConsoleAPICalled(event: Dict) -> None:
args: List[JSHandle] = []
for arg in event.get('args', []):
args.append(jsHandleFactory(arg))
consoleAPICalled(event['type'], args)
self._client.on('Runtime.consoleAPICalled', onConsoleAPICalled)
self._client.on(
'Runtime.exceptionThrown',
lambda exception: exceptionThrown(exception['exceptionDetails']),
)
async def _send(self, method: str, msg: dict) -> None:
try:
await self._client.send(method, msg)
except Exception as e:
debugError(logger, e)
return
scriptId = event.get('scriptId')
url = event.get('url')
if not url and self._reportAnonymousScript:
url = f'debugger://VM{scriptId}'
try:
response = await self._client.send(
'Debugger.getScriptSource',
{'scriptId': scriptId}
)
self._scriptURLs[scriptId] = url
self._scriptSources[scriptId] = response.get('scriptSource')
except Exception as e:
# This might happen if the page has already navigated away.
debugError(logger, e)
text = statusLine + CRLF
for header in responseHeaders:
text = f'{text}{header}: {responseHeaders[header]}{CRLF}'
text = text + CRLF
responseBuffer = text.encode('utf-8')
if responseBody:
responseBuffer = responseBuffer + responseBody
rawResponse = base64.b64encode(responseBuffer).decode('ascii')
try:
await self._client.send('Network.continueInterceptedRequest', {
'interceptionId': self._interceptionId,
'rawResponse': rawResponse,
})
except Exception as e:
debugError(logger, e)