-
-
Notifications
You must be signed in to change notification settings - Fork 539
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Improve copy-to-clipboard button and
ui.clipboard
for non-secure en…
…vironments (#3636) * hide copy-to-clipboard button if clipboard API is unavailable * add documentation * avoid KeyError when a JavaScript function returns `undefined` * add warnings and documentation to `ui.clipboard`
- Loading branch information
1 parent
6ea6db4
commit ed6a955
Showing
3 changed files
with
33 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,15 +1,38 @@ | ||
from .. import json | ||
from ..logging import log | ||
from .javascript import run_javascript | ||
|
||
|
||
async def read() -> str: | ||
"""Read text from the clipboard.""" | ||
return await run_javascript('navigator.clipboard.readText()') | ||
"""Read text from the clipboard. | ||
Note: This function only works in secure contexts (HTTPS or localhost). | ||
""" | ||
result = await run_javascript(''' | ||
if (navigator.clipboard) { | ||
return navigator.clipboard.readText() | ||
} | ||
else { | ||
console.error('Clipboard API is only available in secure contexts (HTTPS or localhost).') | ||
} | ||
''') | ||
if result is None: | ||
log.warning('Clipboard API is only available in secure contexts (HTTPS or localhost).') | ||
return result or '' | ||
|
||
|
||
def write(text: str) -> None: | ||
"""Write text to the clipboard. | ||
Note: This function only works in secure contexts (HTTPS or localhost). | ||
:param text: text to write | ||
""" | ||
run_javascript(f'navigator.clipboard.writeText({json.dumps(text)})') | ||
run_javascript(f''' | ||
if (navigator.clipboard) {{ | ||
navigator.clipboard.writeText({json.dumps(text)}) | ||
}} | ||
else {{ | ||
console.error('Clipboard API is only available in secure contexts (HTTPS or localhost).') | ||
}} | ||
''') |