我想自动播放电影并在 UIWebView 上自动播放下一部电影。我在 UIWebView 上嵌入了 YouTube 播放器,并为 iFrame片段使用了一些 YouTube 播放器 API,但它们效果不佳。
HTML 如下。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style type="text/css">
body {
background-color: #000;
margin: 0;
}
</style>
</head>
<body>
<div id="player"></div>
<script>
var tag = document.createElement("script");
tag.src = "http://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player("player", {
height: "390",
width: "640",
videoId: "UqFvrjhbO8c",
events: {
"onReady": onPlayerReady,
"onStateChange": onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
document.location = "api://didEndedMovie";
}
}
</script>
</body>
</html>
电影结束时,我希望 webview 加载api://didEndedMovie
。然后,WebView 委托将接收到加载的事件,并调用下面的委托方法。
- (void)viewDidLoad
{
[super viewDidLoad];
if (!_htmlTemplate) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"YouTubePlayer" ofType:@"html"];
_htmlTemplate = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
}
NSString *htmlString = [NSString stringWithFormat:_htmlTemplate];
[self.webView loadHTMLString:htmlString baseURL:nil];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSString *requestString = [[request URL] absoluteString];
// if delegate received requests like "api://*", this view controller
// will not move to other views.
if ([requestString rangeOfString:@"api://"].location == NSNotFound) {
return YES;
}
// called when the movie ended
if ([requestString isEqualToString:@"api://didEndedMovie"]) {
NSLog(@"didEndedMovie");
}
return NO;
}
但是,javascript 不起作用......事件onReady
并onStateChange
没有被触发。
在浏览器上,这个 javascript 运行良好。
为什么不触发事件?