Last active
March 26, 2022 16:32
-
-
Save shirakaba/e89b7d055c57a48bab100ab6f2bee9e9 to your computer and use it in GitHub Desktop.
Injecting a stylesheet into a WKWebView
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
// Any website loaded by the WebView can post to the webkit message handler named "myMessageHandler" | |
// by calling this JavaScript API. It's available for use immediately; no need to wait for document load or anything. | |
webkit.messageHandlers.myMessageHandler.postMessage("hello world"); |
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
import WebKit | |
import UIKit | |
class ViewController: UIViewController { | |
let webView: WKWebView = WKWebView(frame: self.view.frame, configuration: WKWebViewConfiguration()) | |
override func loadView() { | |
super.loadView() | |
self.view = webView | |
let userScript: WKUserScript = WKUserScript( | |
source: | |
""" | |
(function injectWebkitAppRegionStyle(){ | |
const styleEle = document.createElement('style'); | |
styleEle.type = 'text/css'; | |
styleEle.innerHTML = 'body { -webkit-app-region: drag; }'; | |
document.head.appendChild(styleEle); | |
})(); | |
""" | |
injectionTime: WKUserScriptInjectionTime.atDocumentStart, | |
forMainFrameOnly: true | |
) | |
self.webView.configuration.userContentController.addUserScript(userScript) | |
// Set up a bridge called "myMessageHandler" by which any website in the WebView can post messages to the Swift app | |
self.webView.configuration.userContentController.add(self, name: "myMessageHandler") | |
guard let url = URL(string: "https://birchlabs.co.uk") else { return; } | |
self.webView.load(URLRequest(url: url)) | |
} | |
} | |
extension ViewController: WKNavigationDelegate { | |
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) -> Void { | |
// We check message.name because you can register various different userContentControllers with different names | |
if(message.name == "myMessageHandler") { | |
// message.body holds the payload. | |
// The website could, for example, post a stringified JSON message and here you could | |
// decode it into a Swift Dictionary. But for now, we're just posting "hello world". | |
print("Message from the WebView: \(message.body)"); | |
return | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment