Wkwebview and Uimenucontroller

WKWebView and UIMenuController

This appears to be fixed in iOS 13 beta 1.

SwiftUI : custom pop menu in WKWebView

it's been 6 months but here is the answer (works perfectly before iOS 16. With iOS 16 the function is deprecated but still works)

everything happens in canPerformAction

class CustomWKWebView: WKWebView{


override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {

let menu = UIMenuController.shared
menu.shared.menuItems = []
let newInstanceItem = UIMenuItem(title: " My Custom Action", action:#selector(myCustomAction))
menu.menuItems = [newInstanceItem]
menu.update()
if action == #selector(copy(_:)) || action == #selector(selectAll(_:)) || action == #selector(myCustomAction)){

return true
}
return false

}

@objc func myCustomAction() {
// your code

}

}

Get selected text from custom UIMenuItem in WKWebView

You can use Javascript for that.

Here's the code from the the answer you used, slightly altered to get the selected text by evaluating Javascript on the WKWebView:

import UIKit
import WebKit

class ViewController: UIViewController {
weak var webView: CustomMenuWebView!

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
prepareWebView()
}

@objc func translateMenuTapped(_ test: Any) {
webView.evaluateJavaScript("window.getSelection().toString()") { (test, error) in
guard let test = test as? String, error == nil else { return }
// ***** Here's the user's selected text *****
print(test)
}
}
}

private extension ViewController {
func prepareWebView() {
addWebViewToView()
loadWebViewContent()
setupCustomMenu()
}

func addWebViewToView() {
let webView = CustomMenuWebView(
frame: view.bounds, configuration: WKWebViewConfiguration())
view.addSubview(webView)
self.webView = webView
}

func loadWebViewContent() {
let url = URL(string: "https://www.google.com")
let request = URLRequest(url: url!)
webView.load(request)
}

func setupCustomMenu() {
let customMenuItem = UIMenuItem(
title: "Translate", action: #selector(ViewController.translateMenuTapped))
UIMenuController.shared.menuItems = [ customMenuItem ]
UIMenuController.shared.update()
}
}

class CustomMenuWebView: WKWebView {
// Turn off all other menu items
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return false
}
}


Related Topics



Leave a reply



Submit