@@ -37,10 +37,11 @@ async def main():
3737
3838import asyncio
3939import base64
40+ import json as _json
4041import typing
4142
4243from cdp import dom , input_ , page , runtime
43- from cdp .connection import CDPConnection
44+ from cdp .connection import CDPConnection , CDPConnectionError
4445
4546__all__ = [
4647 # Navigation
@@ -330,10 +331,28 @@ async def clear_and_type(
330331 else selector_or_node
331332 )
332333 await focus (conn , node )
333- # Select all – platform-agnostic via JavaScript.
334- await conn .execute (
335- runtime .evaluate (expression = "document.execCommand('selectAll', false, null)" )
336- )
334+ # Select all existing content using the modern Selection/input API.
335+ # For input/textarea: element.select(); for contenteditable: window.getSelection().
336+ obj = await conn .execute (dom .resolve_node (node_id = node ))
337+ if obj and obj .object_id :
338+ await conn .execute (
339+ runtime .call_function_on (
340+ function_declaration = (
341+ "function() {"
342+ " if (typeof this.select === 'function') {"
343+ " this.select();"
344+ " } else {"
345+ " var range = document.createRange();"
346+ " range.selectNodeContents(this);"
347+ " var sel = window.getSelection();"
348+ " sel.removeAllRanges();"
349+ " sel.addRange(range);"
350+ " }"
351+ "}"
352+ ),
353+ object_id = obj .object_id ,
354+ )
355+ )
337356 await type_text (conn , node , text , delay = delay )
338357
339358
@@ -396,8 +415,9 @@ async def select_option(
396415 obj = await conn .execute (dom .resolve_node (node_id = node ))
397416 if obj is None :
398417 raise ValueError ("Could not resolve node to a remote object" )
399- escaped = value .replace ("'" , "\\ '" )
400- expr = f"function() {{ this.value = '{ escaped } '; this.dispatchEvent(new Event('change', {{bubbles: true}})); }}"
418+ # Use json.dumps to safely embed the value as a JS string literal.
419+ js_value = _json .dumps (value )
420+ expr = f"function() {{ this.value = { js_value } ; this.dispatchEvent(new Event('change', {{bubbles: true}})); }}"
401421 await conn .execute (
402422 runtime .call_function_on (
403423 function_declaration = expr ,
@@ -711,10 +731,9 @@ async def _wait() -> _T_Event:
711731 async for event in conn .listen ():
712732 if isinstance (event , event_type ):
713733 return event # type: ignore[return-value]
714- raise CDPConnectionError ("Connection closed before event arrived" ) # noqa: F821
734+ raise CDPConnectionError ("Connection closed before event arrived" )
715735
716736 try :
717- from cdp .connection import CDPConnectionError # local import to avoid circular
718737 return await asyncio .wait_for (_wait (), timeout = timeout )
719738 except asyncio .TimeoutError :
720739 raise asyncio .TimeoutError (
0 commit comments