html - 如何让 webview 只加载特定的网站,比如 youtube?

标签 html swift webview youtube

我是 Swift 的新手,我正在制作一个带有 webview 的应用程序,它可以显示 youtube 视频。我的问题是我不希望我的用户转到另一个 url 或类似的东西。我想让我的应用加载 youtube.com。我使用 HTML 而不是 URL,因为我可以告诉我的 webview 它的高度和宽度。

HTML代码:

<html><head><style type=\"text/css\">body {background-color: transparent;color: white;}</style></head><body style=\"margin:0\"><iframe frameBorder=\"0\" height=\"" + String(describing: height) + "\" width=\"" + String(describing: width) + "\" src=\"http://www.youtube.com/embed/" + vid.videoId + "?showinfo=0&modestbranding=1&frameborder=0&rel=0\"></iframe></body></html>

最佳答案

您可以尝试使用 UIWebViewDelegateshouldStartLoadWith 委托(delegate)方法

extension UIViewController: UIWebViewDelegate {

    public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let url = request.url?.absoluteString ?? ""

        print("WebView shouldStartLoadWithRequest url -> \(url)")

        if !url.contains("youtube.com") {

            // avoid loading strange urls..
            // manage error as you need..
            webView.stopLoading()

            return false
        }
        return true
    }
}

请记住在 viewDidLoad 方法中将 UIViewController 设置为 UIWebView 委托(delegate):

override func viewDidLoad() {
    super.viewDidLoad()

    myWebView.delegate = self
}

关于html - 如何让 webview 只加载特定的网站,比如 youtube?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45681085/

相关文章:

javascript - 还记得加载到不同页面时的 li 事件状态吗?

arrays - 如何更改数组字典中元素的值?

ios - Firebase queryEqualToValue 在 Swift 2.3 中获取 Key

arrays - 快速编辑 plist 数组

android webview错误找不到页面

asp.net - 标题属性 - 对于使网页可访问有用吗?

html - Firefox:性能低下且元素模糊

Android webview 从 strings.xml 加载 HTML

javascript - 尝试停止在 react native 中加载 webView 时出现未定义错误

javascript - 使用javascript继承