zoukankan      html  css  js  c++  java
  • js 判断是否可以打开本地软件

    js判断时候可以打开本地的软件或者插件

      点击一个按钮,打开本地的软件,比如问题反馈,需要调起本地的邮箱,填入一些信息。

      这个功能<a>标签有提供支持,但是如果本地没有安装邮箱,则无法打开,点了之后也没有任何反应,那么就需要判断当前电脑或者手机是否已经安装了指定的软件,如果已经安装,则打开该软件,否则,弹出模态框,给用户提示。

      其实这个并不好判断,后来在各大网站中找到一下方法

      1. ActiveXObject

      2. navigator.plugins

    然而这些方法都无效

    最后在GitHub上发现了一个插件 custom-protocol-detection

    在插件中有这样一个原理:如果本地安装了软件,当尝试打开时,window后触发 blur 事件,如果无法打开,则什么都不会发生

    根据这个原理,进行一个非常简单的封装,这里使用的是 vue + es6,只在Chrome或者移动端中可用

    <template>
        <div>
            <p
                class="link"
                data-link="mailto:lihuan10@baidu.com"
                @click="openMailto">
                测试打开邮箱
            </p>
        </div>
    </template>
    
    <script>
    export default {
        name: 'plugin',
        data() {
            return {
                readyToBlur: false,
                hasPlugin: null,
                timeout: 1000,
                timer: null
            }
        },
        methods: {
            openMailto(e) {
                let link = e.target.dataset.link
                this.readyToBlur = true;
                this.hasPlugin = false;
                window.location.href = link;
                this.timer = setTimeout(() => {
                    this.readyToBlur = false;
                    !this.hasPlugin && this.noPlugin('mailto');
                    clearTimeout(this.timer);
                }, this.timeout);
            },
            noPlugin(pluginName) {
                console.log('no plugin ' + pluginName);
            }
        },
        mounted() {
            window.addEventListener('blur', () => {
                if (this.readyToBlur) {
                    this.hasPlugin = true;
                    console.log('has plugin');
                }
            });
        },
    }
    </script>

    打开本地软件(比如邮箱,qq)的方法都是让浏览器的url发生改变,一般有一下方法

    1. 使用 a 标签,并使用 href 属性,<a href="plugin: data">plugin</a>

    2. 使用 window.location.href = 'plugin: data';

    3. 使用 window.open('plugin: data');

    这里使用的是第二种,第一种不好做拦截,第三种无论是否安装都会打开一个新的窗口

    注意:这里设置的 timeout 是根据实际情况而定的,因为有一些软件打开的速度很慢。

  • 相关阅读:
    总结:多校1
    简易数论练习
    2017 多校1
    简易数论函数变换学习
    petrozavodsk1
    Permutacja
    图片上传阿里云oss 数据存入redis List
    tp5实现月统计数据
    es6 新特性
    es6 新特性总结
  • 原文地址:https://www.cnblogs.com/shenjp/p/9803885.html
Copyright © 2011-2022 走看看