Last active
February 7, 2022 21:11
-
-
Save bdashore3/99840514adb4b019dc6d72a1e72e8a38 to your computer and use it in GitHub Desktop.
A paste JS function to override WKWebView's behavior
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
// Drop in paste replacement for WKWebView on MacCatalyst | |
// Includes cases where pasting occurs in the middle of the specified text and highlighted text | |
// Replicates native paste by moving the input textbox on text overflow | |
// (c) 2022, Brian Dashore. | |
// Make sure to have a device check for Mac if you're using MacCatalyst! | |
// iOS and iPadOS will have paste broken with this script! | |
const inputs = document.querySelectorAll("input[type=text]") | |
let alreadyPasted = false | |
for (const input of inputs) { | |
input.addEventListener("paste", (event) => { | |
event.preventDefault() | |
// Don't call paste event two times in a single paste command | |
if (alreadyPasted) { | |
alreadyPasted = false | |
return | |
} | |
const paste = (event.clipboardData || window.clipboardData).getData("text") | |
const beginningString = | |
input.value.substring(0, input.selectionStart) + paste | |
input.value = | |
beginningString + | |
input.value.substring(input.selectionEnd, input.value.length) | |
alreadyPasted = true | |
input.setSelectionRange(beginningString.length, beginningString.length) | |
input.scrollLeft = input.scrollWidth | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment