简体   繁体   English

使用Javascript或HTML检测iOS设备的型号?

[英]Detect model of iOS device using Javascript or HTML?

So I'm serving H.264 .mp4 video on my website. 所以我在我的网站上提供H.264 .mp4视频。 I'm using open source HTML5 video player http://mediaelementjs.com/ . 我正在使用开源HTML5视频播放器http://mediaelementjs.com/ Some visitors are viewing from Safari for iPhone. 一些访问者正在从Safari for iPhone查看。 The iPhone 4 supports video playback only up to 720p, so if I make my videos smaller than that, they work on the 4 and the 4S. iPhone 4仅支持高达720p的视频播放,因此如果我将视频设置为小于此值,则可以使用4和4S。 But the 4S supports video up to 1080p. 但4S支持高达1080p的视频。 So how would I serve a larger video to the 4S and a smaller video to the 4? 那么我如何为4S提供更大的视频,为4提供更小的视频呢? I tried this: 我试过这个:

<video width="640" height="400" id="player" controls="controls" preload="auto">
    <source src="https://s3.amazonaws.com/my-big-1080p-video.mp4" type="video/mp4">
    <source src="https://s3.amazonaws.com/my-small-720p-video.mp4" type="video/mp4">
</video>

But it didn't work. 但它没有用。 The iPhone 4 isn't smart enough to try the second source. iPhone 4不够智能,无法尝试第二个来源。 How can I make my website serve the correct video to the different devices? 如何让我的网站为不同的设备提供正确的视频?

Play 720p video on iPhone 4 — 1080p video on iPhone 4S 在iPhone 4上播放720p视频 - 在iPhone 4S上播放1080p视频

Try this on an iPhone 4 and a 4S ( jsfiddle ) 在iPhone 4和4S( jsfiddle )上试试

 <video src="http://file.brow.sr/1080p.mp4" onerror="this.src='http://file.brow.sr/720p.mp4';" controls loop width="320" height="180"> </video> 

Explanation 说明

Load the 1080p video, then use Javascript's onError to fall back to 720p. 加载1080p视频,然后使用Javascript的onError回退到720p。

Safari will sniff the header of the 1080p file to determine if it's playable, and if it's too big to decode it will throw an error. Safari将嗅探1080p文件的标题以确定它是否可播放,如果它太大而无法解码则会引发错误。 We then catch that error to provide the 720p video. 然后我们捕获该错误以提供720p视频。

By using this kind of feature detection, the fallback will not only work on one device (iPhone 4) but probably on a lot of different capable browsers. 通过使用这种特征检测,后备不仅可以在一个设备(iPhone 4)上运行,而且可能在许多不同功能的浏览器上运行。

Why multiple <source> 's won't work 为什么多个<source>不起作用

When using multiple <source> tags with the same MIME types , the browser will load the first source that has a compatible MIME type and discard the others, even if that video is not playable. 当使用具有相同MIME类型的多个<source>标记 ,浏览器将加载具有兼容MIME类型的第一个源并丢弃其他源,即使该视频不可播放也是如此。 That's because source elements are expected to provide alternative video codecs (eg. ogg, webm, mp4), not alternative frame sizes / file sizes. 这是因为source元素有望提供替代视频编解码器(例如ogg,webm,mp4), 而不是替代帧大小/文件大小。

Here is how to go about it: 以下是如何进行的:

1) Retrieve the device model by using wurfl 1)使用wurfl检索设备模型

<script type='text/javascript' src=“//wurfl.io/wurfl.js"></script>

You can either use HTTP or HTTPS (both are are supported) If you plan to use the device information provided by the script to make rendering decisions, then you might want to include the script in the element. 您可以使用HTTP或HTTPS(两者都受支持)如果您计划使用脚本提供的设备信息来做出渲染决策,那么您可能希望将脚本包含在元素中。 Otherwise, you can load it asynchronously. 否则,您可以异步加载它。 Now you have access to the WURFL object within JavaScript. 现在您可以在JavaScript中访问WURFL对象。

Sample response looks something like: 示例响应类似于:

{ complete_device_name:"Apple iPhone 5", form_factor:"Smartphone", is_mobile:true } {complete_device_name:“Apple iPhone 5”,form_factor:“Smartphone”,is_mobile:true}

off course you can(and should) 当然你可以(而且应该)

console.log(WURFL);

to find out the rest of the properties you can use. 找出你可以使用的其他属性。

2) Now that you know which exactly which device model your users are on, you can switch the video players configs. 2)现在你知道你的用户究竟在哪个设备型号上,你可以切换视频播放器的配置。

How about something like? 怎么样的?

<video width="IPHONE5_VIDEO_WIDTH"
       height="IPHONE5_VIDEO_HEIGHT"
       id="player" controls="controls"
       preload="auto">
       <source src="IPHONE5_VIDEO_URL" type="video/mp4">
</video>

super clean and readable right? 超级干净,可读性好吗? Hope that helps. 希望有所帮助。

I have a php script that does this. 我有一个PHP脚本,这样做。 I got it here - http://detectmobilebrowsers.com/ - and yes, there is a javascript, JQuery, etc. versions. 我在这里得到它 - http://detectmobilebrowsers.com/ - 是的,有一个javascript,JQuery等版本。 It's worked quite well for us and it has the benefit of seeming to stay fairly updated. 它对我们来说效果很好,它的好处似乎是保持相当的更新。 The only issue we've run into was an iPad that had been deliberate set not to identify itself as a mobile device. 我们遇到的唯一问题是iPad被故意设置为不将自己标识为移动设备。

尝试链接库应该能够检测用户代理,您可以相应地提供适当的文件。

I cannot offer sample code since I am not an Apple geek, but I can tell you based off of my experience trying to make sites compatible between XHTML and HTML5 that it is better to check for browser capability than browser version. 我不能提供示例代码,因为我不是Apple的极客,但我可以根据我的经验告诉你,尝试在XHTML和HTML5之间兼容网站,检查浏览器功能比浏览器版本更好。

The reason for this is that there are too many browser versions to justify the upkeep, and also the user agent string can be modified. 这样做的原因是有太多的浏览器版本来证明维护,并且还可以修改用户代理字符串。 I recommend that you write a script that checks for HTML5 video capabilities with a simple if statement, and then render either one video or the other depending upon the results. 我建议您编写一个脚本,使用简单的if语句检查HTML5视频功能,然后根据结果呈现一个视频或另一个视频。

A mobile device detection database like WURFL (Wireless Universal Resource File - http://wurfl.sourceforge.net/ ) or DeviceAtlas may be overkill if video is the only capability you're checking for. 如果视频是您正在检查的唯一功能,则像WURFL(无线通用资源文件 - http://wurfl.sourceforge.net/ )或DeviceAtlas这样的移动设备检测数据库可能会过度。 But it is a quick way to get robust capabilities detection for a vastly larger range of devices than you would be able to feasibly compile checks for, and would come in handy if your site ever needs to verify other capabilities besides video support. 但是,如果您的网站需要验证除视频支持之外的其他功能,那么这一种快速的方法,可以为更大范围的设备获得强大的功能检测,而且可以很方便地编译检查。

Your solution don't work because of the reason mentioned by dear @Duvrai. 由于亲爱的@Duvrai提到的原因,你的解决方案无效。 I've searched to attain a right way to meet your purpose and it seemed we have no choice unless using some javascript code (here without considering server side programming) to make a decision which source should be delivered. 我已经搜索到了达到你的目的的正确方法,似乎我们别无选择,除非使用一些javascript代码(这里不考虑服务器端编程)来决定应该交付哪个源。 The bellow snippet detects the browser Type and its Version : bellow代码段检测浏览器类型及其版本

 navigator.sayswho= (function(){ var ua= navigator.userAgent, tem, M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\\/))\\/?\\s*(\\d+)/i) || []; if(/trident/i.test(M[1])){ tem= /\\brv[ :]+(\\d+)/g.exec(ua) || []; alert('IE '+(tem[1] || '')); } if(M[1]=== 'Chrome'){ tem= ua.match(/\\bOPR\\/(\\d+)/) if(tem!= null) alert('Opera '+tem[1]); } M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?']; if((tem= ua.match(/version\\/(\\d+)/i))!= null) M.splice(1, 1, tem[1]); alert( M.join(' ')); })(); 

Now you can write some lines of code in javascript and decide to change video sources based on browser Type and Version . 现在,您可以在javascript中编写一些代码行,并决定根据浏览器类型版本更改视频源。

MEJS player does not handle errors correctly, I'd to add more support to be able to detect what actually happened. MEJS播放器无法正确处理错误,我会添加更多支持以便能够检测到实际发生的情况。 On iPhone it even sometimes throws an error event but there is no actual error and you can play the video correctly. 在iPhone上它甚至有时会抛出错误事件,但没有实际错误,你可以正确播放视频。

Open mediaelement-and-player.js and look for 打开mediaelement-and-player.js并寻找

        // error handling
        media.addEventListener('error',function() {
            loading.hide();
            controls.find('.mejs-time-buffering').hide();
            error.show();
            error.find('mejs-overlay-error').html("Error loading this resource");
        }, false);

Then use this code: 然后使用此代码:

        // error handling
        media.addEventListener('error',function() {
            var
                videoError = error.closest('.mejs-inner').find('video,audio')[0].error,
                msg = 'Error loading this resource.';

            if (!videoError) { //webkit sometimes throws error event but video has no actual error and can play the video correctly - ignore the event
                console.log('MEJS event: error throws but no error found - ignored');
                return;
            }

            //hide elements visible while loading and playing - cannot play after error
            loading.hide();
            controls.addClass('hidden'); //controls are automatically displayed when mouse hover is detected - must hide it permanently using class with !important
            error.closest('.mejs-inner').find('.mejs-overlay-play').hide(); //also hide overlay with play button
            error.show();

            //get relevant error message
            switch(videoError.code) { //see http://www.w3.org/TR/html5/embedded-content-0.html#error-codes
                case videoError.MEDIA_ERR_ABORTED: //loading stopped (by user, e.g. by pressing ESC or Back)
                    msg = 'Video loading aborted';
                    break;
                case videoError.MEDIA_ERR_DECODE: //invalid format (actually presumed format is OK, but the data does not correspond with the defined format - probably corrupted file of data transfer)
                    msg = 'Video file is broken';
                    break;
                case videoError.MEDIA_ERR_NETWORK: //network problem (was able to connect to the provided URL but could not get the video data)
                    msg = 'Network connection lost';
                    break;
                case videoError.MEDIA_ERR_SRC_NOT_SUPPORTED: //invalid source URL (url provided does not lead to a supported video file)
                    msg = 'Video not supported';
                    break;
            }

            //display error
            console.log('Video error: ' + msg + ', code: ' + videoError.code);
            error.find('.mejs-overlay-error').html(msg);
        }, false);

If you need to you can add your own handling that will switch to 720p in case of unsupported video. 如果需要,您可以添加自己的处理,如果视频不受支持,将切换到720p。

And in mediaelementplayer.css add this (not sure if actually required or just improvement for my theme): 并在mediaelementplayer.css中添加(不确定是否实际需要或仅改进我的主题):

/* Display errors */
.mejs-overlay-error {
    color: white;
    background: black;
    text-align: center;
    font-size: 1.2EM;
}
.mejs-controls.hidden {
    display: none !important;
}
/* End: Display errors */

This is for version 2.13.1, not sure if newer version is better. 这适用于版本2.13.1,不确定更新版本是否更好。

Update: newest version 2.16.3 contains exactly same useless error handler. 更新:最新版本2.16.3包含完全相同的无用错误处理程序。

This will detect the iOS version. 这将检测iOS版本。 Maybe it can be useful: 也许它可能有用:

if (navigator.userAgent.indexOf('5_0') != -1) {
    alert('IOS 5');
} else {
    alert('Other');
}

Edit: I have have ajusted and tested the script. 编辑:我已经调整并测试了脚本。

Put this in your tags: 把它放在你的标签中:

<meta name="viewport" content="initial-scale=1.0">
<meta name="viewport" content="width=320.1">    
<script>
if (window.screen.height==568) { // iPhone 5
                    document.querySelector("meta[name=viewport]").content="width=320.1";
                  // your code here
                }
</script>

I use this code: 我用这个代码:

    // iPhone 3
    if (window.screen.height==480 && window.screen.width==320 && window.devicePixelRatio==1)
    { 
        $('#chartDivWrapper').html('<div id="chartdiv" style="height:300px;width:500px;"></div>');
    } 
    // iPhone 4, this is Retina
    else if (window.screen.height==480 && window.screen.width==320 && window.devicePixelRatio==2) 
    { 
        $('#chartDivWrapper').html('<div id="chartdiv" style="height:300px;width:500px;"></div>');
    } 
    // iPhone 5
    else if (window.screen.height==568 && window.screen.width==320 && window.devicePixelRatio==2) 
    { 
        $('#chartDivWrapper').html('<div id="chartdiv" style="height:400px;width:600px;"></div>');
    } 
    // iPad
    else if (window.screen.height==1024 && window.screen.width==768 && window.devicePixelRatio==1) 
    { 
        $('#chartDivWrapper').html('<div id="chartdiv" style="height:425px;width:680px;"></div>');
    } 
    // iPad Retina
    else if (window.screen.height==1024 && window.screen.width==768 && window.devicePixelRatio==2) 
    { 
        $('#chartDivWrapper').html('<div id="chartdiv" style="height:425px;width:680px;"></div>');
    } 
    // all other, this was before for all 
    else  
    { 
        $('#chartDivWrapper').html('<div id="chartdiv" style="height:400px;width:600px;"></div>');
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 是否可以使用javascript或ASP.Net检测移动设备模型 - Is it possible to detect the mobile device model using javascript or ASP.Net 如何使用HTML和JavaScript检测iOS应用何时进入后台 - How to detect when iOS app goes the background using HTML and JavaScript 如何使用jQuery / JavaScript检测ios设备并仅隐藏iPhone和iPad的Bootstrap模式? - How to Detect ios device using jQuery/JavaScript and hide Bootstrap modal only iPhone and iPad? 使用javascript检测iPad设备方向 - Detect iPad device orientation using javascript 如何使用javascript,css检测浏览器/设备? - How to detect the browser/device using javascript,css? 使用 javascript 检测设备 CPU/GPU 性能? - Using javascript to detect device CPU/GPU performance? 检测设备是否为 iOS - Detect if device is iOS 使用JavaScript检测iOS移动设备比自动播放音频 - Detect iOS Mobile Device with JavaScript than auto play audio 有没有一种方法可以通过Javascript检测是否在(Android \\ iOS)设备上安装了特定应用程序? - Is there a way to detect if a specific app is installed on (Android\iOS) device from Javascript? 有没有一种方法可以检测Javascript / Cordova / HTML5中的设备振动? - Is there a way to detect device vibration in Javascript/Cordova/HTML5?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM