validata.js 2.94 KB
/**
 * 验证码插件
 * @author: feng.chen<feng.chen@yoho.cn>
 * @date: 2017/03/13
 */
let $ = require('yoho-jquery'),
    ImgCheck = require('plugin/img-check');
const validType = {
    IMG_CHECK: 1,
    GEETEST: 2
};

// 解决加载w3t统计代码同时使用geetest报错问题
(() => {
    (typeof SVGAnimatedString !== 'undefined') && (SVGAnimatedString.prototype.indexOf = function() {
        return false;
    });
})();

class Validate {
    constructor(container, options) {
        this.$container = container;
        this.options = options;
        this.type = container.data('geetest') ? validType.GEETEST : validType.IMG_CHECK;
        if (this.type === validType.IMG_CHECK) {
            this.imgCheck = new ImgCheck(this.$container, this.options);
        } else {
            $.ajax({
                url: '/passport/geetest/register?t=' + (new Date()).getTime(), // 加随机数防止缓存(IE下的问题)
                type: 'get',
                dataType: 'json',
                success: data => {
                    window.initGeetest && window.initGeetest({
                        gt: data.gt,
                        challenge: data.challenge,
                        offline: !data.success
                    }, (captchaObj) => {
                        this.captchaObj = captchaObj;
                        captchaObj.appendTo($('#js-img-check'));
                        $('#js-img-check').after('<input id="yohobuy" type="text" style="display:none;">');
                        this._atWorking = true;
                        $('#js-img-check').addClass('hide').addClass('popup');
                    });
                }
            });
            $('.yoho-page').on('touchstart', '#js-img-check', (e) => {
                if ($(e.target).attr('id') !== 'js-img-check') {
                    return;
                }
                $('#js-img-check').addClass('hide');
            });
        }
    }
    get atWorking() {
        return this._atWorking;
    }
    refresh() {
        if (this.type === validType.IMG_CHECK) {
            this.imgCheck.refresh();
        } else {
            this.captchaObj.refresh();
        }
    }
    init() {
        if (this.type === validType.IMG_CHECK) {
            if (this.$container.data('init') != null) { //eslint-disable-line
                this.imgCheck.init();
                this._atWorking = this.imgCheck.atWorking;
            }
        }
    }
    getResults() {
        if (this.type === validType.IMG_CHECK) {
            return this.imgCheck.getResults();
        } else {
            if ($('#yohobuy').val()) {
                return '';
            }
            return new Promise((resolve) => {
                $('#js-img-check').removeClass('hide');
                this.captchaObj.onSuccess(() => {
                    resolve(this.captchaObj.getValidate());
                    $('#js-img-check').addClass('hide');
                });
            });
        }
    }
}

module.exports = Validate;