简体   繁体   English

使用 Javascript 检测桌面浏览器(非移动设备)

[英]Detect Desktop Browser (not mobile) with Javascript

I found the following code to detect a desktop browser.我发现以下代码可以检测桌面浏览器。 But the method also detects some mobile browsers.但该方法也会检测到一些移动浏览器。 How can I detect only desktop browsers like Safari, IE, Firefox, Opera etc?如何只检测桌面浏览器,如 Safari、IE、Firefox、Opera 等?

is_desktopBrowser : function() {
    var ua = navigator.userAgent.toLowerCase();

    var rwebkit = /(webkit)[ \/]([\w.]+)/;
    var ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/;
    var rmsie = /(msie) ([\w.]+)/;
    var rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/;

    var match = rwebkit.exec(ua) ||
            ropera.exec(ua) ||
            rmsie.exec(ua) ||
            ua.indexOf("compatible") < 0 && rmozilla.exec(ua) ||
            [];

    return { browser: match[1] || "", version: match[2] || "0" };
},

jQuery.browser can be helpful when trying to figure out which browser. jQuery.browser 在尝试找出哪个浏览器时会很有帮助。 jQuery.browser was removed in jQuery 1.9. jQuery.browser在 jQuery 1.9 中被移除。

I believe it is based on navigator.UserAgent, however navigator.UserAgent can tell you the OS on its own if you want.我相信它是基于 navigator.UserAgent,但是如果你愿意,navigator.UserAgent 可以自己告诉你操作系统。

Try this:试试这个:

var isMobile = navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)|(android)|(webOS)/i)

source来源

I check for我检查

('ontouchstart' in window)

since that will tell me if I'm on a touch capable device.因为这会告诉我我是否在支持触摸的设备上。 Of course that also returns true for an ipad, which might not be considered a "mobile device", but then I just check window.width for layout purposes.当然,对于可能不被视为“移动设备”的 ipad,这也会返回 true,但我只是出于布局目的检查window.width

I came up with this:我想出了这个:

    var isTouchDevice = function() {  return 'ontouchstart' in window || 'onmsgesturechange' in window; };
    var isDesktop = window.screenX != 0 && !isTouchDevice() ? true : false;

It leverages two things we can hold on to.它利用了我们可以坚持的两件事。 One, window.screenX will ALWAYS be 0 on any tablet / mobile device.一,window.screenX 在任何平板电脑/移动设备上始终为 0。 You can't move windows on these devices, it is always full screen.您无法在这些设备上移动窗口,它始终是全屏的。

Two, isTouchDevice is a pretty reliable way to know if it's mobile (android / iphone tablet) or Windows Surfacey thing.第二,isTouchDevice 是一种非常可靠的方式来了解它是移动设备(android / iphone 平板电脑)还是 Windows Surfacey。 It has a touch event.它有一个触摸事件。 Combining the two gives us a high degree of certainty that it's a mobile or tablet.将两者结合起来可以让我们高度确定它是手机还是平板电脑。 If you're not one of those, you must be desktop.如果您不是其中之一,那么您必须是台式机。

Yes, you might have a desktop that somehow reports itself as touch and has the browser maxxed to the upper left.是的,您可能有一个桌面,不知何故将自己报告为触摸,并将浏览器最大化到左上角。 In my case, I can let that go.在我的情况下,我可以放手。

I have been investigating this for my ReView (Responsive Viewport) project.我一直在为我的 ReView(响应式视口)项目调查这个。 I use a combination of the following.我使用以下组合。

  • window.screenX窗口.screenX

Most mobile browsers have the 'window' locked to the left hand side.大多数移动浏览器都将“窗口”锁定在左侧。 So if this isn't zero, likely to be a desktop browser window.因此,如果这不是零,则可能是桌面浏览器窗口。

  • window.devicePixelRatio and screen.width window.devicePixelRatio 和 screen.width

If dpr is 1 and screen width is reported as large via screen.width, likely to be desktop.如果 dpr 为 1 并且屏幕宽度通过 screen.width 报告为大,则可能是桌面。

  • window.orientation窗口方向

It is rare to find a desktop monitor in portrait mode.很难找到纵向模式的桌面显示器。 However, this could happen.然而,这可能发生。

More unlikely is multiple orientation changes while using your site/app.更不可能的是在使用您的网站/应用程序时多次更改方向。 This implies a desktop user would be spinning their screen... very unlikely.这意味着桌面用户会旋转他们的屏幕......非常不可能。

A combination of these with some common sense and you can achieve a pretty solid guess.将这些与一些常识结合起来,您就可以得出非常可靠的猜测。

The project mentioned along with more info is at http://responsiveviewport.com提到的项目以及更多信息位于http://responsiveviewport.com

Hope that helps.希望有帮助。

Even it's a bit overkill for your case, express-useragent is one of the best solution as it can be used on both server and browser.即使对您的情况来说有点矫枉过正,但express-useragent是最好的解决方案之一,因为它可以在服务器和浏览器上使用。 Your case:你的情况:

Include js file in HTML在 HTML 中包含 js 文件

<script type="text/javascript" src="/path/to/express-useragent.js"></script>

Execute the plugin执行插件

var userAgent = new UserAgent().parse(navigator.userAgent);

Value of userAgent will be something like userAgent值将类似于

{
  "isMobile":false,
  "isDesktop":true,
  "isBot":false,
  .....
  "browser":"Chrome",
  "version":"17.0.963.79",
  "os":"Windows 7",
  "platform":"Microsoft Windows",
  "source":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.79..."
}

You can go to http://detectmobilebrowsers.com and generate a JS script which will detect whether a browser is a mobile browser.您可以访问http://detectmobilebrowsers.com并生成一个 JS 脚本,该脚本将检测浏览器是否为移动浏览器。 Unless you are worried about Smart TVs or some other non mobile nor desktop appliances, you can use that script and assume that if the browser is NOT a mobile browser then it should be a desktop browser.除非您担心智能电视或其他一些非移动或桌面设备,否则您可以使用该脚本并假设如果浏览器不是移动浏览器,那么它应该是桌面浏览器。

Here is an example solution using the regex-es generated by that site:这是使用该站点生成的正则表达式的示例解决方案:

var ua = navigator.userAgent.toLowerCase();
var isDesktop = !(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)));

只需包含Modernizr js 文件,它就会向所有桌面浏览器添加名为 no-touch 的类,以便您可以轻松地使用这些类进行定位

Actually, it is easy to detect mobile or tablet device, then with a simple result inversion we can understand that is desktop or not, for easy accessing I write a simple function:其实很容易检测到手机或平板设备,然后通过一个简单的结果反演我们就可以知道是不是桌面设备,为了方便访问,我写了一个简单的函数:

const isDesktop = () => {
  const navigatorAgent =
    navigator.userAgent || navigator.vendor || window.opera;
  return !(
    /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series([46])0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(
      navigatorAgent
    ) ||
    /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br([ev])w|bumb|bw-([nu])|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do([cp])o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly([-_])|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-([mpt])|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c([- _agpst])|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac([ \-/])|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja([tv])a|jbro|jemu|jigs|kddi|keji|kgt([ /])|klon|kpt |kwc-|kyo([ck])|le(no|xi)|lg( g|\/([klu])|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t([- ov])|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30([02])|n50([025])|n7(0([01])|10)|ne(([cm])-|on|tf|wf|wg|wt)|nok([6i])|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan([adt])|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c([-01])|47|mc|nd|ri)|sgh-|shar|sie([-m])|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel([im])|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c([- ])|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test(
      navigatorAgent.substr(0, 4)
    )
  );
};

Note : this function is based on ES6 and it should transpile, best case for ReactJS .:该功能是基于ES6,它应该为transpile ReactJS,最好的情况。

The problem with your script is, that it's just trying to detect the browser with the UserAgent -string which is not quite accurate because everyone can fake his UserAgent .你的脚本的问题是,它只是试图用UserAgent -string 检测浏览器,这不太准确,因为每个人都可以伪造他的UserAgent

For a pretty good read on browser detection, check out this link: http://www.quirksmode.org/js/detect.html有关浏览器检测的非常好的阅读,请查看此链接: http : //www.quirksmode.org/js/detect.html

As I said here , IE10+ solution just using matchMedia :正如我在这里所说的IE10+解决方案只使用matchMedia

const isMobile = () => window.matchMedia('(max-width: 700px)').matches

isMobile() returns a boolean isMobile()返回一个布尔值

 const isMobile = () => window.matchMedia('(max-width: 700px)').matches document.addEventListener('DOMContentLoaded', () => { setInterval(() => document.querySelector('.result').textContent = isMobile() ? 'yes but you should try this code in a bigger screen' : 'no', 300) }, false);
 .result { color: green; font-weight: bold; }
 Am I on mobile screen? <span class="result">something went wrong :/</span> <p> <div>Click in full page to see the difference</div>

What is the specific feature of a desktop browser that means you want different behaviour?桌面浏览器的具体功能是什么,这意味着您需要不同的行为?

Is it the input mechanism (mouse and physical keyboard vs touch and virtual keyboard), the larger screen size, or something else?是输入机制(鼠标和物理键盘 vs 触摸和虚拟键盘)、更大的屏幕尺寸还是其他原因?

For example, in CSS4 you can use @media (any-pointer: coarse) for touch-enabled devices and@media (pointer: coarse) for devices where the primary input is touch (ie phones and tablets whether or not an external keyboard is plugged in).例如,在 CSS4 中,您可以将@media (any-pointer: coarse)用于支持触摸的设备,将@media (pointer: coarse)用于主要输入为触摸的设备(即手机和平板电脑,无论是否有外部键盘)插入)。 CSS4 is mostly fully supported by modern browsers.现代浏览器大多完全支持 CSS4。

In JavaScript, you can use Window.matchMedia() to test for any CSS media query (including those above) as suggested in this SO answer .在 JavaScript 中,您可以使用Window.matchMedia()来测试任何 CSS 媒体查询(包括上面的那些),如本 SO 答案中所建议的。 (I would have hoped for something more native by now, but couldn't find anything.) (我本来希望现在能找到更本土的东西,但找不到任何东西。)

would this not work? 这不行吗?

window.addEventListener('mousemove', function(){
    // whatever code you want to have on desktop
});

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

相关问题 Javascript 适用于桌面,但不适用于移动浏览器 - Javascript works on desktop but not on mobile browser 检测移动浏览器和javascript支持 - detect mobile browser and javascript support Javascript函数在桌面上可用,在移动浏览器上失败 - Javascript function works on Desktop, fails on mobile browser 查询可在浏览器桌面中使用但不能在移动设备中使用的JavaScript代码 - query mobile code javascript working in browser desktop but not in mobile 用于检测移动浏览器屏幕宽度的Javascript? - Javascript to detect mobile browser screen width? 如果移动浏览器未打开或未激活,则在 Javascript/jQuery 中检测 - Detect in Javascript/jQuery if mobile browser is not open or active 可以在javascript中检测webapp或移动浏览器 - possible to detect webapp or mobile browser in javascript 手机桌面浏览器模拟器 - Desktop Browser Simulators for Mobile 如何从浏览器中使用 JavaScript 打开移动或桌面应用程序? - How to open a mobile or desktop app with JavaScript from the browser? 如何检测salesforce lightning应用程序是在移动浏览器还是台式机浏览器上运行? - How to detect whether salesforce lightning app is running on a mobile browser or desktop browser?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM