2016-12-06 117 views
0

我正在使用WKWebView打開pages in Youtube。問題在於,他們在開場時就開始播放視頻並進入全屏模式,這不是想要的行爲。視頻沒有嵌入,它是整個頁面的描述,評論等。ios - 在WkWebView中禁用Youtube自動播放功能

有沒有辦法阻止他們玩?

+0

我有一個相同的問題。 –

回答

0

它的工作原理。 請閱讀評論。

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) 
     } 
    } 
} 
相關問題