alekop
alekop

Reputation: 3026

Can two WKWebViews be linked via the opener property?

I'm opening a WKWebView from another, and would like the two to be able to communicate with each other via JavaScript.

The following code opens two Web views - I can inspect them with the Safari debugger. But the opener property of the second Web view is null.

class MyVC: UIViewController {
    override func viewDidLoad() {
        ...
        // "webView" is the first web view. Open a second one...
        webView = WKWebView()
        webView.uiDelegate = self
        webView.evaluateJavaScript("window.open('about:blank');")
    }
}


extension MyVC : WKUIDelegate {
    func webView(... createWebViewWith ...) -> WKWebView? {
        let newWebView = WKWebView(frame: webView.bounds,
                                   configuration: configuration)
        newWebView.load(navigationAction.request)

        let vc = UIViewController()
        vc.view.addSubview(newWebView)
        navigationController?.pushViewController(vc, animated: true)

        return nil
    }

}

Is there a way to set the opener property?

Upvotes: 0

Views: 814

Answers (1)

alekop
alekop

Reputation: 3026

The window.opener was null because I was returning nil from the createWebViewWith method. I changed it to return the new web view, and that sets the new window's opener property to "parent" web view.

func webView(... createWebViewWith ...) -> WKWebView? {
    let newWebView = WKWebView(frame: webView.bounds,
    ...
    return newWebView
}

Upvotes: 1

Related Questions