ios - 在WkWebView中禁用Youtube自动播放

时间:2016-12-06 21:32:25

标签: ios webview youtube

我使用WKWebView打开pages in Youtube。问题是,在开放时他们开始播放视频并全屏,这不是通缉行为。视频没有嵌入,它的整个页面包含描述,评论等。

有没有办法阻止他们玩?

1 个答案:

答案 0 :(得分:2)

有效。 请阅读评论。

import UIKit
import WebKit
import RxSwift

class WebViewController: UIViewController {

    let webview: WKWebView

    init() {
        //  add config
        let config = WKWebViewConfiguration()
        config.allowsInlineMediaPlayback = true
        if #available(iOS 10.0, *) {
            config.mediaTypesRequiringUserActionForPlayback = .video
        }
        self.webview = WKWebView(frame: .zero, configuration: config)

        super.init(nibName: nil, bundle: nil)
        webview.frame = view.bounds
        subscribeURL()
    }

    private func subscribeURL() {
        self.webview.rx.url
        .shareReplay(1)
            .subscribe(onNext: { [weak self] url in
                guard let url = url else { return }
                //  Navigation Delegate can not detect transition because YouTube is Single Page Application.
                startInlinePlayApplyInterval()
            })
            .addDisposableTo(disposeBag)
    }

    private func startInlinePlayApplyInterval() {
        //  There is time rag to come out new video element so start repeat interval.
        //Useful Timer extension: http://stackoverflow.com/a/39600244/3276863
        let loop = Timer.schedule(repeatInterval: 0.2) { [weak self] timer in
            self?.applyInlinePlay { success in
                if success {
                    timer?.invalidate()
                }
            }
        }
        Timer.schedule(delay: 2) { _ in
            loop?.invalidate()
        }
    }

    private func applyInlinePlay(completion: @escaping (Bool)->Void) {
        //  add attributes 'webkit-playsinline','playsinline','controls' to video element
        let script = "(function(){var applied=document.querySelector('video').attributes.playsinline!=undefined;if(applied){return false}var videos=document.querySelectorAll('video');var attrList=['webkit-playsinline','playsinline','controls'];for(video of videos){for(attr of attrList){video.setAttribute(attr,'');}}return true})();"
        webview.evaluateJavaScript(script) { res, err in
            let isSuccessToApply: Bool = (res as? Bool) ?? false
            completion(isSuccessToApply)
        }
    }
}