Skip to content

Instantly share code, notes, and snippets.

@shirakaba
Last active March 26, 2022 16:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shirakaba/e89b7d055c57a48bab100ab6f2bee9e9 to your computer and use it in GitHub Desktop.
Save shirakaba/e89b7d055c57a48bab100ab6f2bee9e9 to your computer and use it in GitHub Desktop.
Injecting a stylesheet into a WKWebView
// 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");
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