Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save joseph/cabf174742fd6592ec5c9d79f20bf96d to your computer and use it in GitHub Desktop.
Save joseph/cabf174742fd6592ec5c9d79f20bf96d to your computer and use it in GitHub Desktop.
Add keyboardRequiresUserInteraction to WKWebViews
import WebKit
// This swizzle allows JavaScript to set the focus on an input, not just when a user is interacting.
//
extension WKWebView {
private typealias StartAssistingNodeMethodType = @convention(c) (Any, Selector, UnsafeRawPointer, Bool, Bool, Any) -> Void
private typealias StartAssistingNodeClosureType = @convention(block) (Any, UnsafeRawPointer, Bool, Bool, Any) -> Void
func focusInputsWithoutUserInteraction() {
let selector: Selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:userObject:")
guard let wkContentViewClass: AnyClass = NSClassFromString("WKContentView") else { return }
guard let method = class_getInstanceMethod(wkContentViewClass, selector) else { return }
let original: StartAssistingNodeMethodType = unsafeBitCast(method_getImplementation(method), to: StartAssistingNodeMethodType.self)
let replacement: StartAssistingNodeClosureType = { (me, arg0, arg1, arg2, arg3) in
original(me, selector, arg0, true, arg2, arg3)
}
method_setImplementation(method, imp_implementationWithBlock(replacement))
}
}
@joseph
Copy link
Author

joseph commented Oct 23, 2017

This fork:

  • aims for a more descriptive method name
  • has private typealiases that are named for their purpose
  • follows Swift 3 conventions for variable names
  • guards against a nil result for NSClassFromString or class_getInstanceMethod and returns early
  • trims some cruft

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment