Quantcast
Channel: Active questions tagged youtube-api - Stack Overflow
Viewing all articles
Browse latest Browse all 3832

Variables not available in injected Javascript in iOS WKWebView

$
0
0

I am trying to use the Youtube iframe API in my WKWebView in iOS but am not able to use the player object for calling pauseVideo() etc. functions.

My WKWebView instance is calling its loadHTMLString(string:, baseURL) function using the following script

<iframe id="test-iframe" enablejsapi=true width="854" height="480" frameborder="0" allowfullscreen="allowfullscreen" src="https://www.youtube.com/embed/-hLoU2qP4zc?autoplay=1&amp;start=0&amp;rel=0"><script type="text/javascript">var tag = document.createElement('script');tag.src = 'https://www.youtube.com/iframe_api';var firstScriptTag = document.getElementsByTagName('script')[0];firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);var player;function onYouTubeIframeAPIReady() {  player = new YT.Player('test-iframe');}

then later after the webview has loaded and user has spent good time interacting with the webview the following call is made to pause the video

script = """player.pauseVideo();"""webView.evaluateJavaScript(script) { res, err in    print("completion of JS eval", res, err)}

This raises exception:

completion of JS eval nil Optional(Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=ReferenceError: Can't find variable: player, WKJavaScriptExceptionColumnNumber=11, WKJavaScriptExceptionSourceURL=https://www.youtube.com/, NSLocalizedDescription=A JavaScript exception occurred})

I am not sure what is causing player to be unavailable.Digging deeper I realised that no variable at all are available to the injected code as I tried to declare only this in my script and still failed make it available in my injected code.

Loaded this script using loadHTMLString(string:, baseURL):

<script type="text/javascript">   var testContent = 'test content';</script>

Then injected script:

script = """  window.webkit.messageHandlers.handler.postMessage(testContent.toString());"""webView.evaluateJavaScript(script) { res, err in    print("completion of JS eval", res, err)}

Still gives me the error (removed other messages in error): Can't find variable: testContent

I am trying to understand what could be reason behind this issue of unavailable variables in injected scripts


Viewing all articles
Browse latest Browse all 3832

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>