【问题标题】:Open WebView URL in Browser在浏览器中打开 WebView URL
【发布时间】:2015-06-24 18:02:31
【问题描述】:

我制作了一个非常简单的 Swift 应用程序,它可以加载一个带有链接的网页。每当我单击链接时,它们都不会打开。我将如何在 OS X 的浏览器窗口中打开加载的 .html 网页上的链接?

这是我的实现:

import Cocoa
import WebKit

class ViewController: NSViewController {

    @IBOutlet weak var webView: WebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let urlString = "URL"
        self.webView.mainFrame.loadRequest(NSURLRequest(URL: NSURL(string: urlString)!))
    }

    override var representedObject: AnyObject? {
        didSet {
            // Update the view, if already loaded.
        }
    }
}

【问题讨论】:

  • 如果没有更多信息,就不可能知道发生了什么。请发布您的 UIWebView 代码和任何相关的错误消息。
  • 很抱歉。我将其添加到主帖中。
  • 我刚刚提出了另一个修改来修复标签,因为 uiwebview 应该只用于 iOS 问题。很抱歉混淆了。

标签: macos swift cocoa webview


【解决方案1】:

首先,将WebView 的策略委托和初始 URL 设置为类变量:

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))
}

然后,重写委托方法以拦截导航。

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
    }
}

【讨论】:

  • 谢谢!这似乎奏效了。我可以对菜单项使用相同的方法来让它们在浏览器中打开吗?
  • 您是指FileEdit、...下的选项吗?是的,只需使用NSWorkspace.sharedWorkspace().openURL(someURL)
【解决方案2】:

您还可以决定在 WebView 中打开哪些链接以及在浏览器中打开哪些链接,就像在 html 页面中编写目标属性一样简单

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

并在上面提到的decisionPolicyForNewWindowAction 中使用目标检查。我已将完整答案放在this question 线程中。希望你能自己翻译成swift。

【讨论】:

  • 在使用WebView时,并不总是可以访问网站。
猜你喜欢
  • 2013-02-05
  • 2015-06-19
  • 2016-12-29
  • 1970-01-01
  • 2013-03-11
  • 2014-05-22
  • 2011-07-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多