ChenLiang 4 years ago
commit
104e3e3380
2 changed files with 468 additions and 0 deletions
  1. 280 0
      插件/common.js
  2. 188 0
      插件/playerToJs.js

+ 280 - 0
插件/common.js

@@ -0,0 +1,280 @@
+var comm = {
+    // 添加事件的函数
+    addEvent: function (ele, ev, fn) {
+        //针对IE浏览器
+        if(ele.attachEvent){ 
+            ele.attachEvent('on'+ev,fn)
+        }
+        //针对FF与chrome
+        else{   
+            ele.addEventListener(ev, fn, false)
+        }
+    },
+    // 封装ajax
+    ajax: function (options) {
+        var _this = this;
+        // 创建时间戳,确保每一秒的请求是不同的
+        this.format = function(){
+            var now = new String(new Date().getTime());
+            return now.substr(0,now.length-3);
+        }
+        //格式化参数
+        this.formatParams = function(data) {
+            //获取地址参数
+            var arr = [];
+            for (var name in data) {
+                arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
+            }
+            
+            arr.push("t="+_this.format());//按分钟刷一次
+            return arr.join("&");
+        }
+        
+        //异步请求对象的完成状态
+        this.done = 0;
+        //传入设置
+        options = options || {};
+        //请求方式
+        options.type = (options.type || "GET").toUpperCase();
+        options.dataType = options.dataType || "json";
+        options.async = options.async || true;
+        var params = _this.formatParams(options.data);
+        //创建异步请求对象 - 第一步
+        var xhr;
+        //w3c标准
+        if (window.XMLHttpRequest) {
+            xhr = new XMLHttpRequest();
+        } 
+        //兼容IE6及以下
+        else if (window.ActiveObject) { 
+            xhr = new ActiveXObject('Microsoft.XMLHTTP');
+        }
+        
+        //连接 和 发送 - 第二步
+        //判断是那种类型的请求
+        //若是get请求
+        if (options.type == "GET") {
+            //参数拼接
+            if(options.url.indexOf("?")==-1) sp="?" ; else sp="&";
+        
+            //发送请求
+            xhr.open("GET", options.url + sp + params,options.async);
+            xhr.send(null);
+        } 
+        //若是post请求
+        else if (options.type == "POST") {
+            //发送请求
+            xhr.open("POST", options.url,options.async);
+            //设置表单提交时的内容类型
+            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
+            //参数配置
+            xhr.send(params);
+        }
+
+        //接收 - 第三步
+        xhr.onreadystatechange = function() {
+            if (xhr.readyState == 4) {
+                //状态码
+                var status = xhr.status;
+                //状态码表示成功时,执行成功回调函数
+                if (status >= 200 && status < 300 || status == 304) {
+                    //返回数据的格式
+                    //json字符串
+                    if (options.dataType == "json") {
+                        try{
+                            options.success && options.success(eval("("+xhr.responseText+")"));
+                        }
+                        catch(err){
+                            options.success && options.success(JSON.parse(xhr.responseText), xhr.responseXML);
+                        }
+                    }
+                    //普通字符串
+                    else {
+                        options.success && options.success(xhr.responseText, xhr.responseXML);
+                    }
+                    // 改变状态为完成
+                    _this.done = 1;
+                } 
+                //如果状态码表示失败时调用错误处理回调函数
+                else {
+                    options.error && options.error(status);
+                    // 改变状态为完成
+                    _this.done = 1;
+                }
+            }
+        }
+    },
+    /* ====================================================================================== */
+
+    // 判断一个类是否存在
+    hasClass: function (ele, cls) {
+        return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
+    },
+    // 增加一个类
+    addClass: function (ele, cls) {
+        if (!this.hasClass(ele, cls)) ele.className = ele.className.replace(/(\s*$)/g, "") + " " + cls
+    },
+    // 删除一个类
+    removeClass: function (ele, cls) {
+        if (this.hasClass(ele, cls)) {
+            var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
+            ele.className = ele.className.replace(reg, ' ')
+        }
+    },
+    // 获取某个元素的样式
+    getStyle: function (ele, attr) {
+		var res = '';
+		if (window.getComputedStyle) {
+			res = getComputedStyle(ele)[attr];
+		} else if (ele.currentStyle) {
+			res = ele.currentStyle[attr];
+		} else {
+			res = ele.style[attr];
+		}
+		// 这里返回的样式做了调整,返回必须为字符串,有盒子的样式获取像margin-left会返回纯数字(不含单位px),这样不好处理,统一变成字符串后再对返回结果用正则匹配
+		return res + '';
+    },
+    
+    /* ====================================================================================== */
+
+    // 让一个元素隐藏(display)
+    show: function (ele) {
+        ele.style.display = 'block'
+    },
+    // 让一个元素显示(display)
+    hide: function (ele) {
+        ele.style.display = 'none'
+    },
+    // 判断某个元素的是否显示(display,浅)
+    isShow: function (ele) {
+        var getVisibility = ele.style.display;
+        return getVisibility !== "none";
+    },
+    // 判断某个元素是否显示(display,深)
+    isShowDeel: function (ele) {
+		temp = ele
+		var getVisibility = this.getStyle(temp, 'display');
+		if (getVisibility == 'none') {
+			return false;
+		} else if (temp.tagName == 'BODY') {
+			return true;
+		} else {
+			return this.isShowDeel(temp.parentNode);
+		}
+	},
+    // 让一个元素隐藏(visible)
+    visible: function (ele) {
+        ele.style.visibility = 'visible'
+    },
+    // 让一个元素显示(visible)
+    hidden: function (ele) {
+        ele.style.visibility = 'hidden'
+    },
+
+    /* ====================================================================================== */
+
+    // 为一个元素创建一个子元素
+	addElement: function (ele, tag, cls, data, inner, fn) {
+		// 1、创建新元素
+		var newEle = document.createElement(tag)
+		// 2、设置各种属性(图片地址,自定义属性等)
+		newEle.setAttribute('class', cls);
+		for (var item in data) {
+			newEle.setAttribute(item, data[item]);
+		}
+		// 3、设置内容(innerhtml)
+		newEle.innerHTML = inner ? inner : ''
+		// 4、设置回调函数
+		fn && fn(newEle)
+		// 5、将新元素加入到父元素中
+		ele.appendChild(newEle)
+	},
+
+    /* ====================================================================================== */
+
+    // 设置cookie
+    setCookie: function (name, value, time) {
+        //document.cookie.setPath("/");
+        var hour = time ? time : 8;
+        var exp = new Date();
+        exp.setTime(exp.getTime() + hour * 60 * 60 * 1000);
+        document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/";
+    },
+    // 获取cookie   存在返回值,不存在返回null
+    getCookie: function (name) {
+        var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
+        if (arr = document.cookie.match(reg)) {
+            if (arr[2] != "undefined")
+                return unescape(arr[2]);
+            else return undefined;
+        } else {
+            return null;
+        }
+    },
+
+    /* ====================================================================================== */
+
+    // 获取url的某个参数
+    getQueryString: function (name) {
+        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
+        var r = window.location.search.substr(1).match(reg);
+        if (r != null && unescape(r[2]) != "undefined" && unescape(r[2]) != "null") return unescape(r[2]);
+        return ''; 
+    },
+    // 将对象转换为url参数字符串
+    urlParam: function (data) { 
+		var _this = this;
+		var arr = [];
+		for (var name in data) {
+			arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
+		}
+		return arr.join("&");
+	},
+
+    /* ====================================================================================== */
+
+    // 判断是否为有效手机号
+    isPoneAvailable: function (pone) {
+        var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
+        if (!myreg.test(pone)) {
+            return false;
+        } else {
+            return true;
+        }
+    },
+
+    /* ====================================================================================== */
+
+    // 弹窗,用于测试
+    Debuglog: function (text) {
+        // if(testid.indexOf(gdyx.data.client)<=-1)
+        //return
+        if (typeof printWind == "undefined") {
+            window.printWind = document.createElement("div");
+            window.inner = document.createElement("div");
+            inner.style.width = "600px";
+            inner.style.position = "absolute";
+            inner.style.right = "0px";
+            printWind.appendChild(inner);
+            printWind.style.position = "fixed";
+            printWind.style.right = "0";
+            printWind.style.top = "0";
+            printWind.style.background = "rgba(0,0,0,0.6)";
+            printWind.style.zIndex = "99999";
+            printWind.style.padding = "20px";
+            printWind.style.fontSize = "20px";
+            printWind.style.width = "600px";
+            printWind.style.height = "600px";
+            printWind.style.color = "#0aff08";
+            document.body.appendChild(printWind);
+        }
+        var para = document.createElement("p"); //创建新的<p> 元素
+        para.innerHTML = text;
+        para.setAttribute("class", "newLine");
+        para.style.padding = "5px";
+        inner.appendChild(para);
+        var a = inner.clientHeight - 600;
+        inner.style.top = -a + "px";
+    }
+
+}

+ 188 - 0
插件/playerToJs.js

@@ -0,0 +1,188 @@
+// 前端js与webView的交互
+
+var player = {
+    callbackCode: null,     //客户端操作返回的code
+    targetSeekTime: null,     //快进快退跳转的目标时间
+    seekTimeout: null,      //快进快退的防抖延时器
+    isAding: 0,     //当前播放器播放广告的状态码(未来电视播放器)
+    
+    // 播放视频
+    play: function (obj) {
+        // 设置参数
+        var playConfig = {
+            type: obj.type ? obj.type : 1,    //设置播放类型,默认为1
+            url: obj.url ? obj.url : '',    //通过url播放,type为1时必须填
+            code: obj.code ? obj.code : '',     //通过code播放,type为2时必须填
+            seek_time: obj.seek_time ? obj.seek_time * 1000 : 0,    //设置起始时间,默认为0,传入参数单位为秒
+            x: obj.x ? obj.x : 0,   //播放器位置,左(右)上角的x轴坐标点,默认为0
+            y: obj.y ? obj.y : 0,   //播放器位置,左(右)上角的y轴坐标点,默认为0
+            width: obj.width ? obj.width : 1280,    //播放器大小,宽度,默认为1280
+            height: obj.height ? obj.height : 720,  //播放器大小,高度,默认为720
+            examine_id: obj.examine_id ? obj.examine_id : '',   //未来电视专用审核ID; (对接未来电视播放的地区必填)
+            examine_type: obj.examine_type ? obj.examine_type : ''  //未来电视专用审核类型; (对接未来电视播放的地区必填)
+        }
+        // 播放类型为1时,url不能为空
+        if (playConfig.url == '' && playConfig.type == 1) {
+            console.log('播放类型为1,请设置url');
+            return
+        } 
+        // 播放类型为2是,code不能为空
+        else if (playConfig.code == '' && playConfig.type == 2) {
+            console.log('播放类型为2,请设置code');
+            return
+        }
+        // 播放视频,并记录操作返回的code
+        player.callbackCode = PlayerToJS.play(JSON.stringify(playConfig));
+        //code == 6, 执行成功
+        //code == -1, 执行过程中发生异常,中止执行
+        //code == 7, 参数有误,中止执行
+        //code == 8, 播放对象为空,中止执行
+
+    },
+
+    // 播放器尺寸改变
+    changePlayerSize: function (obj) {
+        // 设置参数
+        var changeConfig = {
+            x: obj.x ? obj.x : 0,
+            y: obj.y ? obj.y : 0,
+            width: obj.width ? obj.width : 1280,
+            height: obj.height ? obj.height : 720,
+        }
+        // 更改播放器尺寸,并记录操作返回的code
+        player.callbackCode = PlayerToJS.change(JSON.stringify(changeConfig));
+        //code == 6, 执行成功
+        //code == -1, 执行过程中发生异常,中止执行
+        //code == 7, 参数有误,中止执行
+        //code == 8, 播放对象为空,中止执行
+        // code == 9, 播放对象为初始化,中止执行
+    },
+
+    // 暂停播放
+    pause: function () {
+        player.callbackCode = PlayerToJS.pause();
+    },
+
+    // 恢复播放
+    resume: function () {
+        player.callbackCode = PlayerToJS.resume();
+    },
+
+    // 结束播放
+    stop: function () {
+        player.callbackCode = PlayerToJS.stop(); 
+    },
+
+    // 快进(秒)
+    forward: function (second) {
+        var _this = this
+        var durationTime = _this.getDurationTime()
+        // 获取当前时长,若用户500毫秒内按过快进快退,则会获取到之前的目标时间
+        var currentTime = _this.targetSeekTime != null ? _this.targetSeekTime : _this.getCurrentTime()
+
+        // 若没有传入参数,则默认设置跳跃时间为总时长的20分之1
+        var time = second ? second : durationTime * 0.05;
+        // 计算要跳跃到的目标时间
+        var targetTime = Math.floor(currentTime + time)
+        // 判断目标时间是否超越视频总时长,是则跳到倒数第二秒,否则跳到目标时间
+        if (targetTime >= durationTime) {
+            targetTime = durationTime - 2
+        }
+          // 记录下目标时间并调用防抖跳转方法
+        _this.targetSeekTime = targetTime
+        _this.playTo()
+    },
+
+    // 快退(秒)
+    backward: function (second) {
+        var _this = this
+        var durationTime = _this.getDurationTime()
+         // 获取当前时长,若用户500毫秒内按过快进快退,则会获取到之前的目标时间
+        var currentTime = _this.targetSeekTime != null ? _this.targetSeekTime : _this.getCurrentTime()
+        $.Debuglog(currentTime)
+        // 若没有传入参数,则默认设置跳跃时间为总时长的20分之1
+        var time = second ? second : durationTime * 0.05;
+        // 计算要跳跃到的目标时间
+        var targetTime = Math.floor(currentTime - time)
+        // 判断目标时间是否低于0,是则跳到倒数第二秒,否则跳到目标时间
+        if (targetTime <= 0) {
+            targetTime = 0
+        }
+        // 记录下目标时间并调用防抖跳转方法
+        _this.targetSeekTime = targetTime
+        _this.playTo()
+    },
+
+    // 进度跳转(秒→毫秒)
+    seek: function (time) {
+        var paramJson = { time : time * 1000 }
+        player.callbackCode = PlayerToJS.seek(JSON.stringify(paramJson));  
+    },
+
+    // 快进快退防抖跳转
+    playTo: function () {
+        var _this = this
+        // 设置500毫秒的防抖
+        clearTimeout(_this.seekTimeout)
+        _this.seekTimeout = setTimeout(function() {
+            // 500毫秒内没有快进快退操作,则正式跳转到目标时间,并清除目标时间
+            
+            _this.seek(_this.targetSeekTime)
+            _this.targetSeekTime = null
+        }, 500)
+    },
+
+    // 获取视频总时长(毫秒→秒)
+    getDurationTime: function () {
+        return PlayerToJS.getDuration() / 1000
+    },
+
+    // 获取视频当前时长(毫秒→秒)
+    getCurrentTime: function () {
+        var _this = this
+        // 若快进快退的目标时间存在,则当前时长应为目标时长
+        var currentTime = _this.targetSeekTime ? _this.targetSeekTime : PlayerToJS.getCurrentPlayTime() / 1000
+        return currentTime
+    },
+
+    // 获取视频当前进度(小数)
+    getProgress: function () {
+        var _this = this
+        var durationTime = _this.getDurationTime()
+        var currentTime = _this.getCurrentTime()
+        return currentTime / durationTime
+    },
+
+    // 获取视频当前进度(百分比字符串)
+    getProgressString: function () {
+        var _this = this
+        var progress = _this.getProgress()
+        return Number(progress * 100).toFixed(3) + '%'
+    },
+
+    // 获取当前播放状态
+    getPlayerStatus: function () {
+        return PlayerToJS.getPlayerStatus()
+        // 1,视频准备中;
+        // 2,播放;
+        // 3,暂停;
+        // 4,缓冲;
+        // 5,播放完成停止播放;
+        // 6,未播放;
+    },
+
+    // VR视角旋转(仅限江苏移动VR大厅项目)
+    rotate: function (x, y) {
+        var rotateConfig = {
+            x: x,
+            y: y
+        }
+        player.callbackCode = PlayerToJS.rotate(JSON.stringify(rotateConfig));
+    },
+
+    // 判断当前播放器是否正在播放广告(仅限未来电视播放器)
+    getCNTVPlayerAding: function () {
+        var _this = this
+        _this.isAding= PlayerToJS. getCNTVPlayerAding ()
+    }
+}