class HubbleWebViewController: UIViewController, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler{
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
private var clientId,clientSecret, token,env : String
init(clientId: String, clientSecret: String, token: String, env: String) {
self.clientSecret = clientSecret
super.init(nibName: nil, bundle: nil)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
override func loadView() {
let userContentController = WKUserContentController()
userContentController.add(self, name: "bridge")
let configuration = WKWebViewConfiguration()
configuration.userContentController = userContentController
webview = WKWebView(frame: .zero, configuration: configuration)
webview.navigationDelegate = self
webview.uiDelegate = self
webview.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
override func viewDidLoad() {
let url = URL(string: "https://vouchers.dev.myhubble.money/classic?clientId="+clientId+"&clientSecret="+clientSecret+"&token="+token)!
webview.load(URLRequest(url: url))
webview.allowsBackForwardNavigationGestures = true
webview.configuration.preferences.javaScriptCanOpenWindowsAutomatically = true
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
if let frame = navigationAction.targetFrame,
webView.load(navigationAction.request)
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let url = navigationAction.request.url else {
let baseUrl = URL(string: "https://vouchers.myhubble.money")! //update to vouchers.dev.myhubble.money for `dev` env
if urlMatchesBaseUrl(url, baseUrl: baseUrl) {
decisionHandler(.allow) // Allow navigation within the web view
openURLExternally(url) // Open URL in external browser
private func urlMatchesBaseUrl(_ url: URL, baseUrl: URL) -> Bool {
// Check if the URL matches the base URL
return url.absoluteString.hasPrefix(baseUrl.absoluteString)
private func openURLExternally(_ url: URL) {
// Open URL in the default browser
UIApplication.shared.open(url, options: [:], completionHandler: nil)