Open WebView URL in Browser

后端 未结 2 1122
傲寒
傲寒 2021-01-15 01:54

I made a very simple Swift application that loads a webpage with links on it. Whenever I click the links, they do not open. How would I got about having the links on the loa

相关标签:
2条回答
  • 2021-01-15 02:23

    First, set your WebView's policy delegate and your initial URL as a class variable:

    let url = NSURL(string: "http://www.google.com/")!
    
    // ...
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        // Do any additional setup after loading the view.
    
        self.webView.policyDelegate = self
    
        self.webView.mainFrame.loadRequest(NSURLRequest(URL: self.url))
    }
    

    Then, override the delegate methods to intercept navigation.

    override func webView(webView: WebView!, decidePolicyForNewWindowAction actionInformation: [NSObject : AnyObject]!, request: NSURLRequest!, newFrameName frameName: String!, decisionListener listener: WebPolicyDecisionListener!) {
        println(__LINE__) // the method is needed, the println is for debugging
    }
    
    
    override func webView(webView: WebView!, decidePolicyForNavigationAction actionInformation: [NSObject : AnyObject]!, request: NSURLRequest!, frame: WebFrame!, decisionListener listener: WebPolicyDecisionListener!) {
        if request.URL!.absoluteString == self.url.absoluteString { // load the initial page
            listener.use() // load the page in the app
        } else { // all other links
            NSWorkspace.sharedWorkspace().openURL(request.URL!) // take the user out of the app and into their default browser
        }
    }
    
    0 讨论(0)
  • 2021-01-15 02:33

    Also you can decide what links to open in WebView and what - in browser as easy as to write target attribute in your html page like

    <a href="http://www.google.com/" target="_blank">external page</a>
    

    And use target check in the decidePolicyForNewWindowAction, menthioned above. I've placed the full answer in this question thread. Hope you can translate it to swift yourself.

    0 讨论(0)
提交回复
热议问题