import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate{
@IBOutlet weak var webVw: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Load a URL
if let url = URL(string: "https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_print") {
let request = URLRequest(url: url)
webVw.load(request)
}
}
}
"Print this page" button not showing anything but loading the same url in safari and clicking the same button showing the print page option.


Sorry I misunderstood you earlier.
So, we need a workaround. We'll employ JavaScript injection using
WKUserScriptto catch thewindow.print()function call within theWKWebView. This is possible due to the interoperability of Swift with JavaScript withinWKWebView.Now, let's dissect the code:
WKUserScriptobject with a JavaScript code snippet that redefines thewindow.print()function. In our version, it sends a message using the WebKit message handler,window.webkit.messageHandlers.printHandler.postMessage('print').WKWebViewvia its configuration, which contains a user content controller. We also add a message handler for 'printHandler', which is going to catch the message we've set up in our JavaScript.Setting up WKWebView: Now, initialize the
WKWebViewwith the configuration. However, the earlier warning arises due to the WebView being assigned to a weak property, which leads to its immediate deallocation. Hence, we're going to leverage the already setWKWebViewfrom the storyboard, which is managed by ARC.URL Loading: Here, we load the URL as usual.
Handling the script message:
WKScriptMessageHandlerprotocol implementation helps us handle the receipt of the print message. When we receive the "printHandler" message, we call a native functionprintPage().UIPrintInteractionControllerto present the system print dialog in theprintPage()function.This solution is somewhat a bridge between the webpage's JavaScript environment and our native code.
Now, if
window.print()function isn't being called as expected, you should inspect the JavaScript code running on the webpage. It's possible that thewindow.print()function is being defined after the page load, overriding your custom function. You can use polling to consistently check for the definition ofwindow.print()function, and replace it with your custom function if it's been overwritten.Finally, this solution assumes that the webpage is executing the
window.print()function to initiate printing. If the page uses a different mechanism, this solution won't work, and we'd need to inspect the page's JavaScript further.