How to use sd method in taiko

Best JavaScript code snippet using taiko

sensorsdata.full.js

Source:sensorsdata.full.js Github

copy

Full Screen

1;2(function(factory) {3 if (typeof exports === 'object' && typeof module === 'object') {4 module.exports = factory();5 } else {6 factory();7 }8})(function() {9 try {10 var sd = {};11 var _ = sd._ = {};12 if (typeof JSON !== 'object') {13 JSON = {}14 }(function() {15 'use strict';16 var rx_one = /^[\],:{}\s]*$/,17 rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,18 rx_three = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,19 rx_four = /(?:^|:|,)(?:\s*\[)+/g,20 rx_escapable = /[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,21 rx_dangerous = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;22 function f(n) {23 return n < 10 ? '0' + n : n24 }25 function this_value() {26 return this.valueOf()27 }28 if (typeof Date.prototype.toJSON !== 'function') {29 Date.prototype.toJSON = function() {30 return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null31 };32 Boolean.prototype.toJSON = this_value;33 Number.prototype.toJSON = this_value;34 String.prototype.toJSON = this_value35 }36 var gap, indent, meta, rep;37 function quote(string) {38 rx_escapable.lastIndex = 0;39 return rx_escapable.test(string) ? '"' + string.replace(rx_escapable, function(a) {40 var c = meta[a];41 return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4)42 }) + '"' : '"' + string + '"'43 }44 function str(key, holder) {45 var i, k, v, length, mind = gap,46 partial, value = holder[key];47 if (value && typeof value === 'object' && typeof value.toJSON === 'function') {48 value = value.toJSON(key)49 }50 if (typeof rep === 'function') {51 value = rep.call(holder, key, value)52 }53 switch (typeof value) {54 case 'string':55 return quote(value);56 case 'number':57 return isFinite(value) ? String(value) : 'null';58 case 'boolean':59 case 'null':60 return String(value);61 case 'object':62 if (!value) {63 return 'null'64 }65 gap += indent;66 partial = [];67 if (Object.prototype.toString.apply(value) === '[object Array]') {68 length = value.length;69 for (i = 0; i < length; i += 1) {70 partial[i] = str(i, value) || 'null'71 }72 v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']';73 gap = mind;74 return v75 }76 if (rep && typeof rep === 'object') {77 length = rep.length;78 for (i = 0; i < length; i += 1) {79 if (typeof rep[i] === 'string') {80 k = rep[i];81 v = str(k, value);82 if (v) {83 partial.push(quote(k) + (gap ? ': ' : ':') + v)84 }85 }86 }87 } else {88 for (k in value) {89 if (Object.prototype.hasOwnProperty.call(value, k)) {90 v = str(k, value);91 if (v) {92 partial.push(quote(k) + (gap ? ': ' : ':') + v)93 }94 }95 }96 }97 v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}';98 gap = mind;99 return v100 }101 }102 if (typeof JSON.stringify !== 'function') {103 meta = {104 '\b': '\\b',105 '\t': '\\t',106 '\n': '\\n',107 '\f': '\\f',108 '\r': '\\r',109 '"': '\\"',110 '\\': '\\\\'111 };112 JSON.stringify = function(value, replacer, space) {113 var i;114 gap = '';115 indent = '';116 if (typeof space === 'number') {117 for (i = 0; i < space; i += 1) {118 indent += ' '119 }120 } else if (typeof space === 'string') {121 indent = space122 }123 rep = replacer;124 if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) {125 throw new Error('JSON.stringify')126 }127 return str('', {128 '': value129 })130 }131 }132 if (typeof JSON.parse !== 'function') {133 JSON.parse = function(text, reviver) {134 var j;135 function walk(holder, key) {136 var k, v, value = holder[key];137 if (value && typeof value === 'object') {138 for (k in value) {139 if (Object.prototype.hasOwnProperty.call(value, k)) {140 v = walk(value, k);141 if (v !== undefined) {142 value[k] = v143 } else {144 delete value[k]145 }146 }147 }148 }149 return reviver.call(holder, key, value)150 }151 text = String(text);152 rx_dangerous.lastIndex = 0;153 if (rx_dangerous.test(text)) {154 text = text.replace(rx_dangerous, function(a) {155 return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4)156 })157 }158 if (rx_one.test(text.replace(rx_two, '@').replace(rx_three, ']').replace(rx_four, ''))) {159 j = eval('(' + text + ')');160 return typeof reviver === 'function' ? walk({161 '': j162 }, '') : j163 }164 throw new SyntaxError('JSON.parse')165 }166 }167 }());168 (function() {169 var ArrayProto = Array.prototype;170 var FuncProto = Function.prototype;171 var ObjProto = Object.prototype;172 var slice = ArrayProto.slice;173 var toString = ObjProto.toString;174 var hasOwnProperty = ObjProto.hasOwnProperty;175 var nativeBind = FuncProto.bind;176 var nativeForEach = ArrayProto.forEach;177 var nativeIndexOf = ArrayProto.indexOf;178 var nativeIsArray = Array.isArray;179 var breaker = {};180 var each = _.each = function(obj, iterator, context) {181 if (obj == null) {182 return false;183 }184 if (nativeForEach && obj.forEach === nativeForEach) {185 obj.forEach(iterator, context);186 } else if (obj.length === +obj.length) {187 for (var i = 0, l = obj.length; i < l; i++) {188 if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) {189 return false;190 }191 }192 } else {193 for (var key in obj) {194 if (hasOwnProperty.call(obj, key)) {195 if (iterator.call(context, obj[key], key, obj) === breaker) {196 return false;197 }198 }199 }200 }201 };202 _.extend = function(obj) {203 each(slice.call(arguments, 1), function(source) {204 for (var prop in source) {205 if (source[prop] !== void 0) {206 obj[prop] = source[prop];207 }208 }209 });210 return obj;211 };212 _.extend2Lev = function(obj) {213 each(slice.call(arguments, 1), function(source) {214 for (var prop in source) {215 if (source[prop] !== void 0) {216 if (_.isObject(source[prop]) && _.isObject(obj[prop])) {217 _.extend(obj[prop], source[prop]);218 } else {219 obj[prop] = source[prop];220 }221 }222 }223 });224 return obj;225 };226 _.coverExtend = function(obj) {227 each(slice.call(arguments, 1), function(source) {228 for (var prop in source) {229 if (source[prop] !== void 0 && obj[prop] === void 0) {230 obj[prop] = source[prop];231 }232 }233 });234 return obj;235 };236 _.isArray = nativeIsArray || function(obj) {237 return toString.call(obj) === '[object Array]';238 };239 _.isFunction = function(f) {240 if (!f) {241 return false;242 }243 try {244 return /^\s*\bfunction\b/.test(f);245 } catch (x) {246 return false;247 }248 };249 _.isArguments = function(obj) {250 return !!(obj && hasOwnProperty.call(obj, 'callee'));251 };252 _.toArray = function(iterable) {253 if (!iterable) {254 return [];255 }256 if (iterable.toArray) {257 return iterable.toArray();258 }259 if (_.isArray(iterable)) {260 return slice.call(iterable);261 }262 if (_.isArguments(iterable)) {263 return slice.call(iterable);264 }265 return _.values(iterable);266 };267 _.values = function(obj) {268 var results = [];269 if (obj == null) {270 return results;271 }272 each(obj, function(value) {273 results[results.length] = value;274 });275 return results;276 };277 _.indexOf = function(arr, target) {278 var indexof = arr.indexOf;279 if (indexof) {280 return indexof.call(arr, target);281 } else {282 for (var i = 0; i < arr.length; i++) {283 if (target === arr[i]) {284 return i;285 }286 }287 return -1;288 }289 };290 _.hasAttribute = function(ele, attr) {291 if (ele.hasAttribute) {292 return ele.hasAttribute(attr);293 } else {294 return !!(ele.attributes[attr] && ele.attributes[attr].specified);295 }296 };297 _.filter = function(arr, fn, self) {298 var hasOwn = Object.prototype.hasOwnProperty;299 if (arr.filter) {300 return arr.filter(fn);301 }302 var ret = [];303 for (var i = 0; i < arr.length; i++) {304 if (!hasOwn.call(arr, i)) {305 continue;306 }307 var val = arr[i];308 if (fn.call(self, val, i, arr)) {309 ret.push(val);310 }311 }312 return ret;313 };314 _.inherit = function(subclass, superclass) {315 subclass.prototype = new superclass();316 subclass.prototype.constructor = subclass;317 subclass.superclass = superclass.prototype;318 return subclass;319 };320 _.trim = function(str) {321 return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');322 };323 _.isObject = function(obj) {324 if (obj == null) {325 return false;326 } else {327 return (toString.call(obj) == '[object Object]');328 }329 };330 _.isEmptyObject = function(obj) {331 if (_.isObject(obj)) {332 for (var key in obj) {333 if (hasOwnProperty.call(obj, key)) {334 return false;335 }336 }337 return true;338 }339 return false;340 };341 _.isUndefined = function(obj) {342 return obj === void 0;343 };344 _.isString = function(obj) {345 return toString.call(obj) == '[object String]';346 };347 _.isDate = function(obj) {348 return toString.call(obj) == '[object Date]';349 };350 _.isBoolean = function(obj) {351 return toString.call(obj) == '[object Boolean]';352 };353 _.isNumber = function(obj) {354 return (toString.call(obj) == '[object Number]' && /[\d\.]+/.test(String(obj)));355 };356 _.isElement = function(obj) {357 return !!(obj && obj.nodeType === 1);358 };359 _.isJSONString = function(str) {360 try {361 JSON.parse(str);362 } catch (e) {363 return false;364 }365 return true;366 };367 _.safeJSONParse = function(str) {368 var val = null;369 try {370 val = JSON.parse(str);371 } catch (e) {372 return false;373 }374 return val;375 };376 _.decodeURIComponent = function(val) {377 var result = val;378 try {379 result = decodeURIComponent(val);380 } catch (e) {381 result = val;382 }383 return result;384 };385 _.encodeDates = function(obj) {386 _.each(obj, function(v, k) {387 if (_.isDate(v)) {388 obj[k] = _.formatDate(v);389 } else if (_.isObject(v)) {390 obj[k] = _.encodeDates(v);391 }392 });393 return obj;394 };395 _.mediaQueriesSupported = function() {396 return (typeof window.matchMedia != "undefined" || typeof window.msMatchMedia != "undefined");397 };398 _.getScreenOrientation = function() {399 var screenOrientationAPI = screen.msOrientation || screen.mozOrientation || (screen.orientation || {}).type;400 var screenOrientation = '未取到值';401 if (screenOrientationAPI) {402 screenOrientation = screenOrientationAPI.indexOf('landscape') > -1 ? 'landscape' : 'portrait';403 } else if (_.mediaQueriesSupported()) {404 var matchMediaFunc = window.matchMedia || window.msMatchMedia;405 if (matchMediaFunc("(orientation: landscape)").matches) {406 screenOrientation = 'landscape';407 } else if (matchMediaFunc("(orientation: portrait)").matches) {408 screenOrientation = 'portrait';409 }410 }411 return screenOrientation;412 };413 _.now = Date.now || function() {414 return new Date().getTime();415 };416 _.throttle = function(func, wait, options) {417 var context, args, result;418 var timeout = null;419 var previous = 0;420 if (!options) options = {};421 var later = function() {422 previous = options.leading === false ? 0 : _.now();423 timeout = null;424 result = func.apply(context, args);425 if (!timeout) context = args = null;426 };427 return function() {428 var now = _.now();429 if (!previous && options.leading === false) previous = now;430 var remaining = wait - (now - previous);431 context = this;432 args = arguments;433 if (remaining <= 0 || remaining > wait) {434 if (timeout) {435 clearTimeout(timeout);436 timeout = null;437 }438 previous = now;439 result = func.apply(context, args);440 if (!timeout) context = args = null;441 } else if (!timeout && options.trailing !== false) {442 timeout = setTimeout(later, remaining);443 }444 return result;445 };446 };447 _.hashCode = function(str) {448 if (typeof str !== 'string') {449 return 0;450 }451 var hash = 0;452 var char = null;453 if (str.length == 0) {454 return hash;455 }456 for (var i = 0; i < str.length; i++) {457 char = str.charCodeAt(i);458 hash = ((hash << 5) - hash) + char;459 hash = hash & hash;460 }461 return hash;462 };463 _.formatDate = function(d) {464 function pad(n) {465 return n < 10 ? '0' + n : n;466 }467 return d.getFullYear() + '-' +468 pad(d.getMonth() + 1) + '-' +469 pad(d.getDate()) + ' ' +470 pad(d.getHours()) + ':' +471 pad(d.getMinutes()) + ':' +472 pad(d.getSeconds()) + '.' +473 pad(d.getMilliseconds());474 };475 _.searchObjDate = function(o) {476 if (_.isObject(o)) {477 _.each(o, function(a, b) {478 if (_.isObject(a)) {479 _.searchObjDate(o[b]);480 } else {481 if (_.isDate(a)) {482 o[b] = _.formatDate(a);483 }484 }485 });486 }487 };488 _.searchZZAppStyle = function(data) {489 if (typeof data.properties.$project !== 'undefined') {490 data.project = data.properties.$project;491 delete data.properties.$project;492 }493 if (typeof data.properties.$token !== 'undefined') {494 data.token = data.properties.$token;495 delete data.properties.$token;496 }497 };498 _.formatJsonString = function(obj) {499 try {500 return JSON.stringify(obj, null, ' ');501 } catch (e) {502 return JSON.stringify(obj);503 }504 };505 _.formatString = function(str) {506 if (str.length > sd.para.max_string_length) {507 sd.log('字符串长度超过限制,已经做截取--' + str);508 return str.slice(0, sd.para.max_string_length);509 } else {510 return str;511 }512 };513 _.searchObjString = function(o) {514 if (_.isObject(o)) {515 _.each(o, function(a, b) {516 if (_.isObject(a)) {517 _.searchObjString(o[b]);518 } else {519 if (_.isString(a)) {520 o[b] = _.formatString(a);521 }522 }523 });524 }525 };526 _.parseSuperProperties = function(obj) {527 if (_.isObject(obj)) {528 _.each(obj, function(value, key) {529 if (_.isFunction(value)) {530 try {531 obj[key] = value();532 if (_.isFunction(obj[key])) {533 sd.log("您的属性- " + key + ' 格式不满足要求,我们已经将其删除');534 delete obj[key];535 }536 } catch (e) {537 delete obj[key];538 sd.log("您的属性- " + key + ' 抛出了异常,我们已经将其删除');539 }540 }541 });542 _.strip_sa_properties(obj);543 }544 };545 _.filterReservedProperties = function(obj) {546 var reservedFields = ['distinct_id', 'user_id', 'id', 'date', 'datetime', 'event', 'events', 'first_id', 'original_id', 'device_id', 'properties', 'second_id', 'time', 'users'];547 if (!_.isObject(obj)) {548 return;549 }550 _.each(reservedFields, function(key, index) {551 if (!(key in obj)) {552 return;553 }554 if (index < 3) {555 delete obj[key];556 sd.log("您的属性- " + key + '是保留字段,我们已经将其删除')557 } else {558 sd.log("您的属性- " + key + '是保留字段,请避免其作为属性名')559 }560 });561 }562 _.searchConfigData = function(data) {563 if (typeof data === 'object' && data.$option) {564 var data_config = data.$option;565 delete data.$option;566 return data_config;567 } else {568 return {};569 }570 }571 _.unique = function(ar) {572 var temp, n = [],573 o = {};574 for (var i = 0; i < ar.length; i++) {575 temp = ar[i];576 if (!(temp in o)) {577 o[temp] = true;578 n.push(temp);579 }580 }581 return n;582 };583 _.strip_sa_properties = function(p) {584 if (!_.isObject(p)) {585 return p;586 }587 _.each(p, function(v, k) {588 if (_.isArray(v)) {589 var temp = [];590 _.each(v, function(arrv) {591 if (_.isString(arrv)) {592 temp.push(arrv);593 } else {594 sd.log('您的数据-', k, v, '的数组里的值必须是字符串,已经将其删除');595 }596 });597 if (temp.length !== 0) {598 p[k] = temp;599 } else {600 delete p[k];601 sd.log('已经删除空的数组');602 }603 }604 if (!(_.isString(v) || _.isNumber(v) || _.isDate(v) || _.isBoolean(v) || _.isArray(v) || _.isFunction(v) || (k === '$option'))) {605 sd.log('您的数据-', k, v, '-格式不满足要求,我们已经将其删除');606 delete p[k];607 }608 });609 return p;610 };611 _.strip_empty_properties = function(p) {612 var ret = {};613 _.each(p, function(v, k) {614 if (v != null) {615 ret[k] = v;616 }617 });618 return ret;619 };620 _.utf8Encode = function(string) {621 string = (string + '').replace(/\r\n/g, '\n').replace(/\r/g, '\n');622 var utftext = '',623 start, end;624 var stringl = 0,625 n;626 start = end = 0;627 stringl = string.length;628 for (n = 0; n < stringl; n++) {629 var c1 = string.charCodeAt(n);630 var enc = null;631 if (c1 < 128) {632 end++;633 } else if ((c1 > 127) && (c1 < 2048)) {634 enc = String.fromCharCode((c1 >> 6) | 192, (c1 & 63) | 128);635 } else {636 enc = String.fromCharCode((c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128);637 }638 if (enc !== null) {639 if (end > start) {640 utftext += string.substring(start, end);641 }642 utftext += enc;643 start = end = n + 1;644 }645 }646 if (end > start) {647 utftext += string.substring(start, string.length);648 }649 return utftext;650 };651 _.base64Encode = function(data) {652 if (typeof btoa === 'function') {653 return btoa(encodeURIComponent(data).replace(/%([0-9A-F]{2})/g, function(match, p1) {654 return String.fromCharCode('0x' + p1);655 }));656 }657 data = String(data);658 var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';659 var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,660 ac = 0,661 enc = '',662 tmp_arr = [];663 if (!data) {664 return data;665 }666 data = _.utf8Encode(data);667 do {668 o1 = data.charCodeAt(i++);669 o2 = data.charCodeAt(i++);670 o3 = data.charCodeAt(i++);671 bits = o1 << 16 | o2 << 8 | o3;672 h1 = bits >> 18 & 0x3f;673 h2 = bits >> 12 & 0x3f;674 h3 = bits >> 6 & 0x3f;675 h4 = bits & 0x3f;676 tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);677 } while (i < data.length);678 enc = tmp_arr.join('');679 switch (data.length % 3) {680 case 1:681 enc = enc.slice(0, -2) + '==';682 break;683 case 2:684 enc = enc.slice(0, -1) + '=';685 break;686 }687 return enc;688 };689 _.UUID = (function() {690 var T = function() {691 var d = 1 * new Date(),692 i = 0;693 while (d == 1 * new Date()) {694 i++;695 }696 return d.toString(16) + i.toString(16);697 };698 var R = function() {699 return Math.random().toString(16).replace('.', '');700 };701 var UA = function(n) {702 var ua = navigator.userAgent,703 i, ch, buffer = [],704 ret = 0;705 function xor(result, byte_array) {706 var j, tmp = 0;707 for (j = 0; j < byte_array.length; j++) {708 tmp |= (buffer[j] << j * 8);709 }710 return result ^ tmp;711 }712 for (i = 0; i < ua.length; i++) {713 ch = ua.charCodeAt(i);714 buffer.unshift(ch & 0xFF);715 if (buffer.length >= 4) {716 ret = xor(ret, buffer);717 buffer = [];718 }719 }720 if (buffer.length > 0) {721 ret = xor(ret, buffer);722 }723 return ret.toString(16);724 };725 return function() {726 var se = String(screen.height * screen.width);727 if (se && /\d{5,}/.test(se)) {728 se = se.toString(16);729 } else {730 se = String(Math.random() * 31242).replace('.', '').slice(0, 8);731 }732 var val = (T() + '-' + R() + '-' + UA() + '-' + se + '-' + T());733 if (val) {734 return val;735 } else {736 return (String(Math.random()) + String(Math.random()) + String(Math.random())).slice(2, 15);737 }738 };739 })();740 _.getQueryParam = function(url, param) {741 param = param.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");742 url = _.decodeURIComponent(url);743 var regexS = "[\\?&]" + param + "=([^&#]*)",744 regex = new RegExp(regexS),745 results = regex.exec(url);746 if (results === null || (results && typeof(results[1]) !== 'string' && results[1].length)) {747 return '';748 } else {749 return _.decodeURIComponent(results[1]);750 }751 };752 _.urlParse = function(para) {753 var URLParser = function(a) {754 this._fields = {755 Username: 4,756 Password: 5,757 Port: 7,758 Protocol: 2,759 Host: 6,760 Path: 8,761 URL: 0,762 QueryString: 9,763 Fragment: 10764 };765 this._values = {};766 this._regex = null;767 this._regex = /^((\w+):\/\/)?((\w+):?(\w+)?@)?([^\/\?:]+):?(\d+)?(\/?[^\?#]+)?\??([^#]+)?#?(\w*)/;768 if (typeof a != 'undefined') {769 this._parse(a)770 }771 };772 URLParser.prototype.setUrl = function(a) {773 this._parse(a)774 };775 URLParser.prototype._initValues = function() {776 for (var a in this._fields) {777 this._values[a] = ''778 }779 };780 URLParser.prototype.addQueryString = function(queryObj) {781 if (typeof queryObj !== 'object') {782 return false;783 }784 var query = this._values.QueryString || '';785 for (var i in queryObj) {786 if (new RegExp(i + '[^&]+').test(query)) {787 query = query.replace(new RegExp(i + '[^&]+'), i + '=' + queryObj[i]);788 } else {789 if (query.slice(-1) === '&') {790 query = query + i + '=' + queryObj[i];791 } else {792 if (query === '') {793 query = i + '=' + queryObj[i];794 } else {795 query = query + '&' + i + '=' + queryObj[i];796 }797 }798 }799 }800 this._values.QueryString = query;801 };802 URLParser.prototype.getUrl = function() {803 var url = '';804 url += this._values.Origin;805 url += this._values.Port ? ':' + this._values.Port : '';806 url += this._values.Path;807 url += this._values.QueryString ? '?' + this._values.QueryString : '';808 url += this._values.Fragment ? '#' + this._values.Fragment : '';809 return url;810 };811 URLParser.prototype.getUrl = function() {812 var url = '';813 url += this._values.Origin;814 url += this._values.Port ? ':' + this._values.Port : '';815 url += this._values.Path;816 url += this._values.QueryString ? '?' + this._values.QueryString : '';817 return url;818 };819 URLParser.prototype._parse = function(a) {820 this._initValues();821 var b = this._regex.exec(a);822 if (!b) {823 throw 'DPURLParser::_parse -> Invalid URL'824 }825 for (var c in this._fields) {826 if (typeof b[this._fields[c]] != 'undefined') {827 this._values[c] = b[this._fields[c]]828 }829 }830 this._values['Hostname'] = this._values['Host'].replace(/:\d+$/, '');831 this._values['Origin'] = this._values['Protocol'] + '://' + this._values['Hostname'];832 };833 return new URLParser(para);834 };835 _.addEvent = function() {836 function fixEvent(event) {837 if (event) {838 event.preventDefault = fixEvent.preventDefault;839 event.stopPropagation = fixEvent.stopPropagation;840 event._getPath = fixEvent._getPath;841 }842 return event;843 }844 fixEvent._getPath = function() {845 var ev = this;846 var polyfill = function() {847 try {848 var element = ev.target;849 var pathArr = [element];850 if (element === null || element.parentElement === null) {851 return [];852 }853 while (element.parentElement !== null) {854 element = element.parentElement;855 pathArr.unshift(element);856 }857 return pathArr;858 } catch (err) {859 return [];860 }861 };862 return this.path || (this.composedPath && this.composedPath()) || polyfill();863 };864 fixEvent.preventDefault = function() {865 this.returnValue = false;866 };867 fixEvent.stopPropagation = function() {868 this.cancelBubble = true;869 };870 var register_event = function(element, type, handler) {871 var useCapture = _.isObject(sd.para.heatmap) && sd.para.heatmap.useCapture ? true : false;872 if (element && element.addEventListener) {873 element.addEventListener(type, function(e) {874 e._getPath = fixEvent._getPath;875 handler.call(this, e);876 }, useCapture);877 } else {878 var ontype = 'on' + type;879 var old_handler = element[ontype];880 element[ontype] = makeHandler(element, handler, old_handler);881 }882 };883 function makeHandler(element, new_handler, old_handlers) {884 var handler = function(event) {885 event = event || fixEvent(window.event);886 if (!event) {887 return undefined;888 }889 event.target = event.srcElement;890 var ret = true;891 var old_result, new_result;892 if (typeof old_handlers === 'function') {893 old_result = old_handlers(event);894 }895 new_result = new_handler.call(element, event);896 if ((false === old_result) || (false === new_result)) {897 ret = false;898 }899 return ret;900 };901 return handler;902 }903 register_event.apply(null, arguments);904 };905 _.addHashEvent = function(callback) {906 var hashEvent = ('pushState' in window.history ? 'popstate' : 'hashchange');907 _.addEvent(window, hashEvent, callback);908 };909 _.addSinglePageEvent = function(callback) {910 var current_url = location.href;911 var historyPushState = window.history.pushState;912 var historyReplaceState = window.history.replaceState;913 window.history.pushState = function() {914 historyPushState.apply(window.history, arguments);915 callback(current_url);916 current_url = location.href;917 };918 window.history.replaceState = function() {919 historyReplaceState.apply(window.history, arguments);920 callback(current_url);921 current_url = location.href;922 };923 var singlePageEvent = historyPushState ? 'popstate' : 'hashchange';924 _.addEvent(window, singlePageEvent, function() {925 callback(current_url);926 current_url = location.href;927 });928 };929 _.cookie = {930 get: function(name) {931 var nameEQ = name + '=';932 var ca = document.cookie.split(';');933 for (var i = 0; i < ca.length; i++) {934 var c = ca[i];935 while (c.charAt(0) == ' ') {936 c = c.substring(1, c.length);937 }938 if (c.indexOf(nameEQ) == 0) {939 return _.decodeURIComponent(c.substring(nameEQ.length, c.length));940 }941 }942 return null;943 },944 set: function(name, value, days, cross_subdomain, is_secure) {945 cross_subdomain = typeof cross_subdomain === 'undefined' ? sd.para.cross_subdomain : cross_subdomain;946 var cdomain = '',947 expires = '',948 secure = '';949 days = days == null ? 73000 : days;950 if (cross_subdomain) {951 var domain = _.getCurrentDomain(location.href);952 if (domain === 'url解析失败') {953 domain = '';954 }955 cdomain = ((domain) ? '; domain=' + domain : '');956 }957 if (days !== 0) {958 var date = new Date();959 if (String(days).slice(-1) === 's') {960 date.setTime(date.getTime() + (Number(String(days).slice(0, -1)) * 1000));961 } else {962 date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));963 }964 expires = '; expires=' + date.toGMTString();965 }966 if (is_secure) {967 secure = '; secure';968 }969 document.cookie = name + '=' + encodeURIComponent(value) + expires +970 '; path=/' + cdomain + secure;971 },972 remove: function(name, cross_subdomain) {973 cross_subdomain = typeof cross_subdomain === 'undefined' ? sd.para.cross_subdomain : cross_subdomain;974 _.cookie.set(name, '', -1, cross_subdomain);975 },976 getCookieName: function(name_prefix, url) {977 var sub = '';978 url = url || location.href;979 if (sd.para.cross_subdomain === false) {980 try {981 sub = _.URL(url).hostname;982 } catch (e) {983 sd.log(e);984 }985 if (typeof sub === 'string' && sub !== '') {986 sub = 'sajssdk_2015_' + name_prefix + '_' + sub.replace(/\./g, '_');987 } else {988 sub = 'sajssdk_2015_root_' + name_prefix;989 }990 } else {991 sub = 'sajssdk_2015_cross_' + name_prefix;992 }993 return sub;994 },995 getNewUser: function() {996 var prefix = 'new_user';997 if (this.get('sensorsdata_is_new_user') !== null || this.get(this.getCookieName(prefix)) !== null) {998 return true;999 } else {1000 return false;1001 }1002 }1003 };1004 _.getElementContent = function(target, tagName) {1005 var textContent = '';1006 var element_content = '';1007 if (target.textContent) {1008 textContent = _.trim(target.textContent);1009 } else if (target.innerText) {1010 textContent = _.trim(target.innerText);1011 }1012 if (textContent) {1013 textContent = textContent.replace(/[\r\n]/g, ' ').replace(/[ ]+/g, ' ').substring(0, 255);1014 }1015 element_content = textContent || '';1016 if (tagName === 'input' || tagName === 'INPUT') {1017 if (target.type === 'button' || target.type === 'submit') {1018 element_content = target.value || '';1019 } else if (sd.para.heatmap && (typeof sd.para.heatmap.collect_input === 'function') && sd.para.heatmap.collect_input(target)) {1020 element_content = target.value || '';1021 }1022 }1023 return element_content;1024 };1025 _.getEleInfo = function(obj) {1026 if (!obj.target) {1027 return false;1028 }1029 var target = obj.target;1030 var tagName = target.tagName.toLowerCase();1031 var props = {};1032 props.$element_type = tagName;1033 props.$element_name = target.getAttribute('name');1034 props.$element_id = target.getAttribute('id');1035 props.$element_class_name = typeof target.className === 'string' ? target.className : null;1036 props.$element_target_url = target.getAttribute('href');1037 props.$element_content = _.getElementContent(target, tagName);1038 props = _.strip_empty_properties(props);1039 props.$url = location.href;1040 props.$url_path = location.pathname;1041 props.$title = document.title;1042 props.$viewport_width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 0;1043 return props;1044 };1045 _.localStorage = {1046 get: function(name) {1047 return window.localStorage.getItem(name);1048 },1049 parse: function(name) {1050 var storedValue;1051 try {1052 storedValue = JSON.parse(_.localStorage.get(name)) || null;1053 } catch (err) {1054 sd.log(err);1055 }1056 return storedValue;1057 },1058 set: function(name, value) {1059 window.localStorage.setItem(name, value);1060 },1061 remove: function(name) {1062 window.localStorage.removeItem(name);1063 },1064 isSupport: function() {1065 var supported = true;1066 try {1067 var key = '__sensorsdatasupport__';1068 var val = 'testIsSupportStorage';1069 _.localStorage.set(key, val);1070 if (_.localStorage.get(key) !== val) {1071 supported = false;1072 }1073 _.localStorage.remove(key);1074 } catch (err) {1075 supported = false;1076 }1077 return supported;1078 }1079 };1080 _.sessionStorage = {1081 isSupport: function() {1082 var supported = true;1083 var key = '__sensorsdatasupport__';1084 var val = 'testIsSupportStorage';1085 try {1086 if (sessionStorage && sessionStorage.setItem) {1087 sessionStorage.setItem(key, val);1088 sessionStorage.removeItem(key, val);1089 supported = true;1090 } else {1091 supported = false;1092 }1093 } catch (e) {1094 supported = false;1095 }1096 return supported;1097 }1098 };1099 _.isSupportCors = function() {1100 if (typeof window.XMLHttpRequest === 'undefined') {1101 return false;1102 }1103 if ('withCredentials' in new XMLHttpRequest()) {1104 return true;1105 } else if (typeof XDomainRequest !== "undefined") {1106 return true;1107 } else {1108 return false;1109 }1110 };1111 _.xhr = function(cors) {1112 if (cors) {1113 if (typeof window.XMLHttpRequest !== 'undefined' && ("withCredentials" in new XMLHttpRequest())) {1114 return new XMLHttpRequest();1115 } else if (typeof XDomainRequest !== "undefined") {1116 return new XDomainRequest();1117 } else {1118 return null;1119 }1120 } else {1121 if (typeof window.XMLHttpRequest !== 'undefined') {1122 return new XMLHttpRequest();1123 }1124 if (window.ActiveXObject) {1125 try {1126 return new ActiveXObject('Msxml2.XMLHTTP')1127 } catch (d) {1128 try {1129 return new ActiveXObject('Microsoft.XMLHTTP')1130 } catch (d) {1131 sd.log(d);1132 }1133 }1134 }1135 }1136 };1137 _.ajax = function(para) {1138 para.timeout = para.timeout || 20000;1139 para.credentials = (typeof para.credentials) === 'undefined' ? true : para.credentials;1140 function getJSON(data) {1141 if (!data) {1142 return '';1143 }1144 try {1145 return JSON.parse(data);1146 } catch (e) {1147 return {};1148 }1149 }1150 var g = _.xhr(para.cors);1151 if (!g) {1152 return false;1153 }1154 if (!para.type) {1155 para.type = para.data ? 'POST' : 'GET';1156 }1157 para = _.extend({1158 success: function() {},1159 error: function() {}1160 }, para);1161 try {1162 if (typeof g === 'object' && ('timeout' in g)) {1163 g.timeout = para.timeout;1164 } else {1165 setTimeout(function() {1166 g.abort();1167 }, para.timeout + 500);1168 }1169 } catch (e) {1170 try {1171 setTimeout(function() {1172 g.abort();1173 }, para.timeout + 500);1174 } catch (e2) {1175 sd.log(e2);1176 };1177 };1178 g.onreadystatechange = function() {1179 try {1180 if (g.readyState == 4) {1181 if ((g.status >= 200 && g.status < 300) || g.status == 304) {1182 para.success(getJSON(g.responseText));1183 } else {1184 para.error(getJSON(g.responseText), g.status);1185 }1186 g.onreadystatechange = null;1187 g.onload = null;1188 }1189 } catch (e) {1190 g.onreadystatechange = null;1191 g.onload = null;1192 };1193 };1194 g.open(para.type, para.url, true);1195 try {1196 if (para.credentials) {1197 g.withCredentials = true;1198 }1199 if (_.isObject(para.header)) {1200 for (var i in para.header) {1201 g.setRequestHeader(i, para.header[i]);1202 }1203 }1204 if (para.data) {1205 if (!para.cors) {1206 g.setRequestHeader("X-Requested-With", "XMLHttpRequest");1207 }1208 if (para.contentType === 'application/json') {1209 g.setRequestHeader("Content-type", "application/json; charset=UTF-8");1210 } else {1211 g.setRequestHeader("Content-type", "application/x-www-form-urlencoded");1212 }1213 }1214 } catch (e) {1215 sd.log(e);1216 };1217 g.send(para.data || null);1218 };1219 _.loadScript = function(para) {1220 para = _.extend({1221 success: function() {},1222 error: function() {},1223 appendCall: function(g) {1224 document.getElementsByTagName('head')[0].appendChild(g);1225 }1226 }, para);1227 var g = null;1228 if (para.type === 'css') {1229 g = document.createElement('link');1230 g.rel = 'stylesheet';1231 g.href = para.url;1232 }1233 if (para.type === 'js') {1234 g = document.createElement('script');1235 g.async = 'async';1236 g.setAttribute('charset', 'UTF-8');1237 g.src = para.url;1238 g.type = 'text/javascript';1239 }1240 g.onload = g.onreadystatechange = function() {1241 if (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') {1242 para.success();1243 g.onload = g.onreadystatechange = null;1244 }1245 };1246 g.onerror = function() {1247 para.error();1248 g.onerror = null;1249 };1250 para.appendCall(g);1251 };1252 _.getHostname = function(url, defaultValue) {1253 if (!defaultValue || typeof defaultValue !== "string") {1254 defaultValue = "hostname解析异常";1255 }1256 var hostname = null;1257 try {1258 hostname = _.URL(url).hostname;1259 } catch (e) {1260 sd.log(e);1261 }1262 return hostname || defaultValue;1263 };1264 _.getQueryParamsFromUrl = function(url) {1265 var result = {};1266 var arr = url.split('?');1267 var queryString = arr[1] || '';1268 if (queryString) {1269 result = _.getURLSearchParams('?' + queryString);1270 }1271 return result;1272 };1273 _.getURLSearchParams = function(queryString) {1274 queryString = queryString || "";1275 var decodeParam = function(str) {1276 return decodeURIComponent(str);1277 };1278 var args = {};1279 var query = queryString.substring(1);1280 var pairs = query.split("&");1281 for (var i = 0; i < pairs.length; i++) {1282 var pos = pairs[i].indexOf('=');1283 if (pos === -1) continue;1284 var name = pairs[i].substring(0, pos);1285 var value = pairs[i].substring(pos + 1);1286 name = decodeParam(name);1287 value = decodeParam(value);1288 args[name] = value;1289 }1290 return args;1291 };1292 _.URL = function(url) {1293 var result = {};1294 var basicProps = ['hash', 'host', 'hostname', 'href', 'origin', 'password', 'pathname', 'port', 'protocol', 'search', 'username'];1295 var isURLAPIWorking = function() {1296 var url;1297 try {1298 url = new URL('http://modernizr.com/');1299 return url.href === 'http://modernizr.com/';1300 } catch (e) {1301 return false;1302 }1303 };1304 if (typeof window.URL === 'function' && isURLAPIWorking()) {1305 result = new URL(url);1306 if (!result.searchParams) {1307 result.searchParams = (function() {1308 var params = _.getURLSearchParams(result.search);1309 return {1310 get: function(searchParam) {1311 return params[searchParam];1312 }1313 };1314 })();1315 }1316 } else {1317 var _regex = /^https?:\/\/.+/;1318 if (_regex.test(url) === false) {1319 throw 'Invalid URL';1320 }1321 var link = document.createElement('a');1322 link.href = url;1323 for (var i = basicProps.length - 1; i >= 0; i--) {1324 var prop = basicProps[i];1325 result[prop] = link[prop];1326 }1327 if (result.hostname && typeof result.pathname === "string" && result.pathname.indexOf('/') !== 0) {1328 result.pathname = '/' + result.pathname;1329 }1330 result.searchParams = (function() {1331 var params = _.getURLSearchParams(result.search);1332 return {1333 get: function(searchParam) {1334 return params[searchParam];1335 }1336 };1337 })();1338 }1339 return result;1340 };1341 _.getCurrentDomain = function(url) {1342 var sdDomain = sd.para.current_domain;1343 switch (typeof(sdDomain)) {1344 case "function":1345 var resultDomain = sdDomain();1346 if (resultDomain === "" || _.trim(resultDomain) === "") {1347 return 'url解析失败';1348 } else if (resultDomain.indexOf(".") !== -1) {1349 return resultDomain;1350 } else {1351 return "url解析失败";1352 }1353 case "string":1354 if (sdDomain === "" || _.trim(sdDomain) === "") {1355 return 'url解析失败';1356 } else if (sdDomain.indexOf(".") !== -1) {1357 return sdDomain;1358 } else {1359 return "url解析失败";1360 }1361 default:1362 var cookieTopLevelDomain = _.getCookieTopLevelDomain();1363 if (url === '') {1364 return 'url解析失败';1365 } else if (cookieTopLevelDomain === '') {1366 return 'url解析失败';1367 } else {1368 return cookieTopLevelDomain;1369 }1370 }1371 };1372 _.getCookieTopLevelDomain = function(hostname) {1373 hostname = hostname || window.location.hostname;1374 var splitResult = hostname.split('.');1375 if (_.isArray(splitResult) && splitResult.length >= 2 && !/^(\d+\.)+\d+$/.test(hostname)) {1376 var domainStr = '.' + splitResult.splice(splitResult.length - 1, 1);1377 while (splitResult.length > 0) {1378 domainStr = '.' + splitResult.splice(splitResult.length - 1, 1) + domainStr;1379 document.cookie = "sensorsdata_domain_test=true; path=/; domain=" + domainStr;1380 if (document.cookie.indexOf('sensorsdata_domain_test=true') !== -1) {1381 var now = new Date();1382 now.setTime(now.getTime() - 1000);1383 document.cookie = "sensorsdata_domain_test=true; expires=" + now.toGMTString() + "; path=/; domain=" + domainStr;1384 return domainStr;1385 }1386 }1387 }1388 return '';1389 };1390 _.isReferralTraffic = function(refererstring) {1391 refererstring = refererstring || document.referrer;1392 if (refererstring === "") {1393 return true;1394 }1395 return _.getCookieTopLevelDomain(_.getHostname(refererstring)) !== _.getCookieTopLevelDomain();1396 };1397 _.ry = function(dom) {1398 return new _.ry.init(dom);1399 };1400 _.ry.init = function(dom) {1401 this.ele = dom;1402 };1403 _.ry.init.prototype = {1404 addClass: function(para) {1405 var classes = ' ' + this.ele.className + ' ';1406 if (classes.indexOf(' ' + para + ' ') === -1) {1407 this.ele.className = this.ele.className + (this.ele.className === '' ? '' : ' ') + para;1408 }1409 return this;1410 },1411 removeClass: function(para) {1412 var classes = ' ' + this.ele.className + ' ';1413 if (classes.indexOf(' ' + para + ' ') !== -1) {1414 this.ele.className = classes.replace(' ' + para + ' ', ' ').slice(1, -1);1415 }1416 return this;1417 },1418 hasClass: function(para) {1419 var classes = ' ' + this.ele.className + ' ';1420 if (classes.indexOf(' ' + para + ' ') !== -1) {1421 return true;1422 } else {1423 return false;1424 }1425 },1426 attr: function(key, value) {1427 if (typeof key === 'string' && _.isUndefined(value)) {1428 return this.ele.getAttribute(key);1429 }1430 if (typeof key === 'string') {1431 value = String(value);1432 this.ele.setAttribute(key, value);1433 }1434 return this;1435 },1436 offset: function() {1437 var rect = this.ele.getBoundingClientRect();1438 if (rect.width || rect.height) {1439 var doc = this.ele.ownerDocument;1440 var docElem = doc.documentElement;1441 return {1442 top: rect.top + window.pageYOffset - docElem.clientTop,1443 left: rect.left + window.pageXOffset - docElem.clientLeft1444 };1445 } else {1446 return {1447 top: 0,1448 left: 01449 }1450 }1451 },1452 getSize: function() {1453 if (!window.getComputedStyle) {1454 return {1455 width: this.ele.offsetWidth,1456 height: this.ele.offsetHeight1457 };1458 }1459 try {1460 var bounds = this.ele.getBoundingClientRect();1461 return {1462 width: bounds.width,1463 height: bounds.height1464 };1465 } catch (e) {1466 return {1467 width: 0,1468 height: 01469 };1470 }1471 },1472 getStyle: function(value) {1473 if (this.ele.currentStyle) {1474 return this.ele.currentStyle[value];1475 } else {1476 return this.ele.ownerDocument.defaultView.getComputedStyle(this.ele, null).getPropertyValue(value);1477 }1478 },1479 wrap: function(elementTagName) {1480 var ele = document.createElement(elementTagName);1481 this.ele.parentNode.insertBefore(ele, this.ele);1482 ele.appendChild(this.ele);1483 return _.ry(ele);1484 },1485 getCssStyle: function(prop) {1486 var result = this.ele.style.getPropertyValue(prop);1487 if (result) {1488 return result;1489 }1490 var rules = null;1491 if (typeof window.getMatchedCSSRules === 'function') {1492 rules = getMatchedCSSRules(this.ele);1493 }1494 if (!rules || !_.isArray(rules)) {1495 return null;1496 }1497 for (var i = rules.length - 1; i >= 0; i--) {1498 var r = rules[i];1499 result = r.style.getPropertyValue(prop);1500 if (result) {1501 return result;1502 }1503 }1504 },1505 sibling: function(cur, dir) {1506 while ((cur = cur[dir]) && cur.nodeType !== 1) {}1507 return cur;1508 },1509 next: function() {1510 return this.sibling(this.ele, "nextSibling");1511 },1512 prev: function(elem) {1513 return this.sibling(this.ele, "previousSibling");1514 },1515 siblings: function(elem) {1516 return this.siblings((this.ele.parentNode || {}).firstChild, this.ele);1517 },1518 children: function(elem) {1519 return this.siblings(this.ele.firstChild);1520 },1521 parent: function() {1522 var parent = this.ele.parentNode;1523 parent = parent && parent.nodeType !== 11 ? parent : null;1524 return _.ry(parent);1525 }1526 };1527 _.strToUnicode = function(str) {1528 if (typeof str !== 'string') {1529 sd.log('转换unicode错误', str);1530 return str;1531 }1532 var nstr = '';1533 for (var i = 0; i < str.length; i++) {1534 nstr += '\\' + str.charCodeAt(i).toString(16);1535 }1536 return nstr;1537 };1538 _.getReferrer = function(referrer) {1539 var referrer = referrer || document.referrer;1540 if (typeof referrer !== 'string') {1541 return '取值异常_referrer异常_' + String(referrer);1542 }1543 if (referrer.indexOf("https://www.baidu.com/") === 0) {1544 referrer = referrer.split('?')[0];1545 }1546 referrer = referrer.slice(0, sd.para.max_referrer_string_length);1547 return (typeof referrer === 'string' ? referrer : '');1548 };1549 _.getKeywordFromReferrer = function(referrerUrl) {1550 referrerUrl = referrerUrl || document.referrer;1551 var search_keyword = sd.para.source_type.keyword;1552 if (document && typeof referrerUrl === 'string') {1553 if (referrerUrl.indexOf('http') === 0) {1554 var searchEngine = _.getReferSearchEngine(referrerUrl);1555 var query = _.getQueryParamsFromUrl(referrerUrl);1556 if (_.isEmptyObject(query)) {1557 return '未取到值';1558 }1559 var temp = null;1560 for (var i in search_keyword) {1561 if (searchEngine === i) {1562 if (typeof query === 'object') {1563 temp = search_keyword[i];1564 if (_.isArray(temp)) {1565 for (var i = 0; i < temp.length; i++) {1566 var _value = query[temp[i]];1567 if (_value) {1568 return _value;1569 }1570 }1571 } else if (query[temp]) {1572 return query[temp];1573 }1574 }1575 }1576 }1577 return '未取到值';1578 } else {1579 if (referrerUrl === '') {1580 return '未取到值_直接打开';1581 } else {1582 return '未取到值_非http的url';1583 }1584 }1585 } else {1586 return '取值异常_referrer异常_' + String(referrerUrl);1587 }1588 };1589 _.getReferSearchEngine = function(referrerUrl) {1590 var hostname = _.getHostname(referrerUrl);1591 if (!hostname || hostname === 'hostname解析异常') {1592 return '';1593 }1594 var search_keyword = sd.para.source_type.keyword;1595 var searchEngineUrls = {1596 baidu: [/^.*\.baidu\.com$/],1597 bing: [/^.*\.bing\.com$/],1598 google: [/^www\.google\.com$/, /^www\.google\.com\.[a-z]{2}$/, /^www\.google\.[a-z]{2}$/],1599 sm: [/^m\.sm\.cn$/],1600 so: [/^.+\.so\.com$/],1601 sogou: [/^.*\.sogou\.com$/],1602 yahoo: [/^.*\.yahoo\.com$/]1603 };1604 for (var prop in searchEngineUrls) {1605 var urls = searchEngineUrls[prop];1606 for (var i = 0, len = urls.length; i < len; i++) {1607 if (urls[i].test(hostname)) {1608 return prop;1609 }1610 }1611 }1612 return '未知搜索引擎';1613 };1614 _.getSourceFromReferrer = function() {1615 function getMatchStrFromArr(arr, str) {1616 for (var i = 0; i < arr.length; i++) {1617 if (str.split('?')[0].indexOf(arr[i]) !== -1) {1618 return true;1619 }1620 }1621 }1622 var utm_reg = '(' + sd.para.source_type.utm.join('|') + ')\\=[^&]+';1623 var search_engine = sd.para.source_type.search;1624 var social_engine = sd.para.source_type.social;1625 var referrer = document.referrer || '';1626 var url = _.info.pageProp.url;1627 if (url) {1628 var utm_match = url.match(new RegExp(utm_reg));1629 if (utm_match && utm_match[0]) {1630 return '付费广告流量';1631 } else if (getMatchStrFromArr(search_engine, referrer)) {1632 return '自然搜索流量';1633 } else if (getMatchStrFromArr(social_engine, referrer)) {1634 return '社交网站流量';1635 } else if (referrer === '') {1636 return '直接流量';1637 } else {1638 return '引荐流量';1639 }1640 } else {1641 return '获取url异常';1642 }1643 };1644 _.info = {1645 initPage: function() {1646 var referrer = _.getReferrer();1647 var url = location.href;1648 var url_domain = _.getCurrentDomain(url);1649 if (!url_domain) {1650 sd.debug.jssdkDebug('url_domain异常_' + url + '_' + url_domain);1651 }1652 this.pageProp = {1653 referrer: referrer,1654 referrer_host: referrer ? _.getHostname(referrer) : "",1655 url: url,1656 url_host: _.getHostname(url, 'url_host取值异常'),1657 url_domain: url_domain1658 };1659 },1660 pageProp: {},1661 campaignParams: function() {1662 var campaign_keywords = sd.source_channel_standard.split(' '),1663 kw = '',1664 params = {};1665 if (_.isArray(sd.para.source_channel) && sd.para.source_channel.length > 0) {1666 campaign_keywords = campaign_keywords.concat(sd.para.source_channel);1667 campaign_keywords = _.unique(campaign_keywords);1668 }1669 _.each(campaign_keywords, function(kwkey) {1670 kw = _.getQueryParam(location.href, kwkey);1671 if (kw.length) {1672 params[kwkey] = kw;1673 }1674 });1675 return params;1676 },1677 campaignParamsStandard: function(prefix, prefix_add) {1678 prefix = prefix || '';1679 prefix_add = prefix_add || '';1680 var utms = _.info.campaignParams();1681 var $utms = {},1682 otherUtms = {};1683 for (var i in utms) {1684 if ((' ' + sd.source_channel_standard + ' ').indexOf(' ' + i + ' ') !== -1) {1685 $utms[prefix + i] = utms[i];1686 } else {1687 otherUtms[prefix_add + i] = utms[i];1688 }1689 }1690 return {1691 $utms: $utms,1692 otherUtms: otherUtms1693 };1694 },1695 properties: function() {1696 return {1697 $screen_height: Number(screen.height) || 0,1698 $screen_width: Number(screen.width) || 0,1699 $lib: 'js',1700 $lib_version: String(sd.lib_version)1701 };1702 },1703 currentProps: {},1704 register: function(obj) {1705 _.extend(_.info.currentProps, obj);1706 }1707 };1708 _.autoExeQueue = function() {1709 var queue = {1710 items: [],1711 enqueue: function(val) {1712 this.items.push(val);1713 this.start();1714 },1715 dequeue: function() {1716 return this.items.shift();1717 },1718 getCurrentItem: function() {1719 return this.items[0];1720 },1721 isRun: false,1722 start: function() {1723 if (this.items.length > 0 && !this.isRun) {1724 this.isRun = true;1725 this.getCurrentItem().start();1726 }1727 },1728 close: function() {1729 this.dequeue();1730 this.isRun = false;1731 this.start();1732 }1733 };1734 return queue;1735 };1736 _.trackLink = function(obj, event_name, event_prop) {1737 obj = obj || {};1738 var link = null;1739 if (obj.ele) {1740 link = obj.ele;1741 }1742 if (obj.event) {1743 if (obj.target) {1744 link = obj.target;1745 } else {1746 link = obj.event.target;1747 }1748 }1749 event_prop = event_prop || {};1750 if (!link || (typeof link !== 'object')) {1751 return false;1752 }1753 if (!link.href || /^javascript/.test(link.href) || link.target || link.download || link.onclick) {1754 sd.track(event_name, event_prop);1755 return false;1756 }1757 function linkFunc(e) {1758 e.stopPropagation();1759 e.preventDefault();1760 var hasCalled = false;1761 function track_a_click() {1762 if (!hasCalled) {1763 hasCalled = true;1764 location.href = link.href;1765 }1766 }1767 setTimeout(track_a_click, 1000);1768 sd.track(event_name, event_prop, track_a_click);1769 }1770 if (obj.event) {1771 linkFunc(obj.event);1772 }1773 if (obj.ele) {1774 _.addEvent(obj.ele, 'click', function(e) {1775 linkFunc(e);1776 });1777 }1778 };1779 _.eventEmitter = function() {1780 this._events = [];1781 this.pendingEvents = [];1782 }1783 _.eventEmitter.prototype = {1784 emit: function(type) {1785 var args = [].slice.call(arguments, 1);1786 _.each(this._events, function(val) {1787 if (val.type !== type) {1788 return;1789 }1790 val.callback.apply(val.context, args);1791 })1792 },1793 on: function(event, callback, context) {1794 if (typeof callback !== 'function') {1795 return;1796 }1797 this._events.push({1798 type: event,1799 callback: callback,1800 context: context || this1801 });1802 },1803 tempAdd: function(event, data) {1804 if (!data || !event) {1805 return;1806 }1807 this.pendingEvents.push({1808 type: event,1809 data: data1810 });1811 this.pendingEvents.length > 20 ? this.pendingEvents.shift() : null;1812 },1813 isReady: function() {1814 var that = this;1815 this.tempAdd = this.emit;1816 if (this.pendingEvents.length === 0) {1817 return;1818 }1819 _.each(this.pendingEvents, function(val) {1820 that.emit(val.type, val.data);1821 })1822 this.pendingEvents = [];1823 }1824 }1825 })();1826 sd.para_default = {1827 preset_properties: {1828 latest_utm: true,1829 latest_traffic_source_type: true,1830 latest_search_keyword: true,1831 latest_referrer: true,1832 latest_referrer_host: false,1833 latest_landing_page: false,1834 url: false,1835 title: false1836 },1837 img_use_crossorigin: false,1838 name: 'sa',1839 max_referrer_string_length: 200,1840 max_string_length: 500,1841 cross_subdomain: true,1842 show_log: true,1843 is_debug: false,1844 debug_mode: false,1845 debug_mode_upload: false,1846 session_time: 0,1847 use_client_time: false,1848 source_channel: [],1849 send_type: 'image',1850 vtrack_ignore: {},1851 auto_init: true,1852 is_track_single_page: false,1853 is_single_page: false,1854 batch_send: false,1855 source_type: {},1856 callback_timeout: 200,1857 datasend_timeout: 3000,1858 queue_timeout: 300,1859 is_track_device_id: false,1860 ignore_oom: true,1861 app_js_bridge: false1862 };1863 sd.addReferrerHost = function(data) {1864 var defaultHost = "取值异常";1865 if (_.isObject(data.properties)) {1866 if (data.properties.$first_referrer) {1867 data.properties.$first_referrer_host = _.getHostname(data.properties.$first_referrer, defaultHost);1868 }1869 if (data.type === "track" || data.type === "track_signup") {1870 if ('$referrer' in data.properties) {1871 data.properties.$referrer_host = data.properties.$referrer === "" ? "" : _.getHostname(data.properties.$referrer, defaultHost);1872 }1873 if (sd.para.preset_properties.latest_referrer && sd.para.preset_properties.latest_referrer_host) {1874 data.properties.$latest_referrer_host = data.properties.$latest_referrer === "" ? "" : _.getHostname(data.properties.$latest_referrer, defaultHost);1875 }1876 }1877 }1878 };1879 sd.addPropsHook = function(data) {1880 if (sd.para.preset_properties && sd.para.preset_properties.url && (data.type === "track" || data.type === "track_signup") && typeof data.properties.$url === 'undefined') {1881 data.properties.$url = window.location.href;1882 }1883 if (sd.para.preset_properties && sd.para.preset_properties.title && (data.type === "track" || data.type === "track_signup") && typeof data.properties.$title === 'undefined') {1884 data.properties.$title = document.title;1885 }1886 };1887 sd.initPara = function(para) {1888 sd.para = para || sd.para || {};1889 var latestObj = {};1890 if (_.isObject(sd.para.is_track_latest)) {1891 for (var latestProp in sd.para.is_track_latest) {1892 latestObj['latest_' + latestProp] = sd.para.is_track_latest[latestProp];1893 }1894 }1895 sd.para.preset_properties = _.extend({}, sd.para_default.preset_properties, latestObj, sd.para.preset_properties || {});1896 var app_js_bridge_default = {1897 is_send: true,1898 white_list: [],1899 H5verify: false,1900 };1901 if (sd.para.use_app_track === true || sd.para.app_js_bridge === true) {1902 if (sd.para.use_app_track_is_send === false) {1903 sd.para.app_js_bridge_default.is_send = false;1904 }1905 sd.para.app_js_bridge = _.extend({}, app_js_bridge_default);1906 } else if (typeof sd.para.app_js_bridge === 'object') {1907 sd.para.app_js_bridge = _.extend({}, app_js_bridge_default, sd.para.app_js_bridge);1908 } else if (sd.para.use_app_track === 'only' || sd.para.use_app_track === 'mui') {1909 sd.para.app_js_bridge = sd.para.use_app_track;1910 }1911 function initAppH5Status() {1912 function checkProjectAndHost(appUrl) {1913 function getHostNameAndProject(url) {1914 var obj = {1915 hostname: '',1916 project: ''1917 };1918 try {1919 obj.hostname = _.URL(url).hostname;1920 obj.project = _.URL(url).searchParams.get('project') || 'default';1921 } catch (e) {1922 console.log(e);1923 }1924 return obj;1925 }1926 var appObj = getHostNameAndProject(appUrl);1927 var H5Obj = getHostNameAndProject(sd.para.server_url);1928 if (appObj.hostname === H5Obj.hostname && appObj.project === H5Obj.project) {1929 return true;1930 } else {1931 if (sd.para.app_js_bridge.white_list[0]) {1932 for (var i = 0; i < sd.para.app_js_bridge.white_list.length; i++) {1933 var urlobj = getHostNameAndProject(sd.para.app_js_bridge.white_list[i]);1934 if (urlobj.hostname === appObj.hostname && urlobj.project === appObj.project) {1935 return true;1936 }1937 }1938 }1939 }1940 return false;1941 }1942 if (_.isObject(sd.para.app_js_bridge)) {1943 if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.sensorsdataNativeTracker && _.isObject(window.SensorsData_iOS_JS_Bridge) && window.SensorsData_iOS_JS_Bridge.sensorsdata_app_server_url) {1944 if (checkProjectAndHost(window.SensorsData_iOS_JS_Bridge.sensorsdata_app_server_url)) {1945 sd.para.app_js_bridge.H5verify = true;1946 }else{1947 sd.para.app_js_bridge.defineModeDebugInfo = '4'1948 }1949 } else if (_.isObject(window.SensorsData_APP_New_H5_Bridge) && window.SensorsData_APP_New_H5_Bridge.sensorsdata_get_server_url && window.SensorsData_APP_New_H5_Bridge.sensorsdata_track) {1950 var app_server_url = window.SensorsData_APP_New_H5_Bridge.sensorsdata_get_server_url();1951 if (app_server_url) {1952 if (checkProjectAndHost(app_server_url)) {1953 sd.para.app_js_bridge.H5verify = true;1954 }else{1955 sd.para.app_js_bridge.defineModeDebugInfo = '4'1956 }1957 }1958 } else {}1959 } else {}1960 }1961 initAppH5Status();1962 var i;1963 for (i in sd.para_default) {1964 if (sd.para[i] === void 0) {1965 sd.para[i] = sd.para_default[i];1966 }1967 }1968 if (typeof sd.para.server_url === 'string' && sd.para.server_url.slice(0, 3) === '://') {1969 sd.para.server_url = location.protocol.slice(-1) + sd.para.server_url;1970 }1971 if (typeof sd.para.web_url === 'string' && sd.para.web_url.slice(0, 3) === '://') {1972 sd.para.web_url = location.protocol.slice(-1) + sd.para.web_url;1973 }1974 if (sd.para.send_type !== 'image' && sd.para.send_type !== 'ajax' && sd.para.send_type !== 'beacon') {1975 sd.para.send_type = 'image';1976 }1977 var batch_send_default = {1978 datasend_timeout: 6000,1979 send_interval: 6000,1980 one_send_max_length: 61981 };1982 if (_.localStorage.isSupport() && _.isSupportCors() && typeof localStorage === 'object') {1983 if (sd.para.batch_send === true) {1984 sd.para.batch_send = _.extend({}, batch_send_default);1985 sd.para.use_client_time = true;1986 } else if (typeof sd.para.batch_send === 'object') {1987 sd.para.use_client_time = true;1988 sd.para.batch_send = _.extend({}, batch_send_default, sd.para.batch_send);1989 }1990 } else {1991 sd.para.batch_send = false;1992 }1993 var utm_type = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term'];1994 var search_type = ['www.baidu.', 'm.baidu.', 'm.sm.cn', 'so.com', 'sogou.com', 'youdao.com', 'google.', 'yahoo.com/', 'bing.com/', 'ask.com/'];1995 var social_type = ['weibo.com', 'renren.com', 'kaixin001.com', 'douban.com', 'qzone.qq.com', 'zhihu.com', 'tieba.baidu.com', 'weixin.qq.com'];1996 var search_keyword = {1997 baidu: ['wd', 'word', 'kw', 'keyword'],1998 google: 'q',1999 bing: 'q',2000 yahoo: 'p',2001 sogou: ['query', 'keyword'],2002 so: 'q',2003 sm: 'q'2004 };2005 if (typeof sd.para.source_type === 'object') {2006 sd.para.source_type.utm = _.isArray(sd.para.source_type.utm) ? sd.para.source_type.utm.concat(utm_type) : utm_type;2007 sd.para.source_type.search = _.isArray(sd.para.source_type.search) ? sd.para.source_type.search.concat(search_type) : search_type;2008 sd.para.source_type.social = _.isArray(sd.para.source_type.social) ? sd.para.source_type.social.concat(social_type) : social_type;2009 sd.para.source_type.keyword = _.isObject(sd.para.source_type.keyword) ? _.extend(search_keyword, sd.para.source_type.keyword) : search_keyword;2010 }2011 if (_.isObject(sd.para.heatmap)) {2012 sd.para.heatmap.clickmap = sd.para.heatmap.clickmap || 'default';2013 sd.para.heatmap.scroll_notice_map = sd.para.heatmap.scroll_notice_map || 'default';2014 sd.para.heatmap.scroll_delay_time = sd.para.heatmap.scroll_delay_time || 4000;2015 sd.para.heatmap.scroll_event_duration = sd.para.heatmap.scroll_event_duration || 18000;2016 sd.para.heatmap.renderRefreshTime = sd.para.heatmap.renderRefreshTime || 1000;2017 sd.para.heatmap.loadTimeout = sd.para.heatmap.loadTimeout || 1000;2018 }2019 if (typeof sd.para.server_url === 'object' && sd.para.server_url.length) {2020 for (i = 0; i < sd.para.server_url.length; i++) {2021 if (!/sa\.gif[^\/]*$/.test(sd.para.server_url[i])) {2022 sd.para.server_url[i] = sd.para.server_url[i].replace(/\/sa$/, '/sa.gif').replace(/(\/sa)(\?[^\/]+)$/, '/sa.gif$2');2023 }2024 }2025 } else if (!/sa\.gif[^\/]*$/.test(sd.para.server_url)) {2026 sd.para.server_url = sd.para.server_url.replace(/\/sa$/, '/sa.gif').replace(/(\/sa)(\?[^\/]+)$/, '/sa.gif$2');2027 }2028 if (typeof sd.para.server_url === 'string') {2029 sd.para.debug_mode_url = sd.para.debug_mode_url || sd.para.server_url.replace('sa.gif', 'debug');2030 }2031 if (sd.para.noCache === true) {2032 sd.para.noCache = '?' + (new Date()).getTime();2033 } else {2034 sd.para.noCache = '';2035 }2036 if (sd.para.callback_timeout > sd.para.datasend_timeout) {2037 sd.para.datasend_timeout = sd.para.callback_timeout;2038 }2039 if (sd.para.callback_timeout > sd.para.queue_timeout) {2040 sd.para.queue_timeout = sd.para.callback_timeout;2041 }2042 if (sd.para.queue_timeout > sd.para.datasend_timeout) {2043 sd.para.datasend_timeout = sd.para.queue_timeout;2044 }2045 };2046 sd.readyState = {2047 state: 0,2048 historyState: [],2049 stateType: {2050 '1': '1-init未开始',2051 '2': '2-init开始',2052 '3': '3-store完成'2053 },2054 getState: function() {2055 return this.historyState.join('\n');2056 },2057 setState: function(n) {2058 if (String(n) in this.stateType) {2059 this.state = n;2060 }2061 this.historyState.push(this.stateType[n]);2062 }2063 };2064 sd.setPreConfig = function(sa) {2065 sd.para = sa.para;2066 sd._q = sa._q;2067 };2068 sd.setInitVar = function() {2069 sd._t = sd._t || 1 * new Date();2070 sd.lib_version = '1.15.1';2071 sd.is_first_visitor = false;2072 sd.source_channel_standard = 'utm_source utm_medium utm_campaign utm_content utm_term';2073 };2074 sd.log = function() {2075 if ((_.sessionStorage.isSupport() && sessionStorage.getItem('sensorsdata_jssdk_debug') === 'true') || sd.para.show_log) {2076 if (sd.para.show_log === true || sd.para.show_log === 'string' || sd.para.show_log === false) {2077 arguments[0] = _.formatJsonString(arguments[0]);2078 }2079 if (typeof console === 'object' && console.log) {2080 try {2081 return console.log.apply(console, arguments);2082 } catch (e) {2083 console.log(arguments[0]);2084 }2085 }2086 }2087 };2088 sd.enableLocalLog = function() {2089 if (_.sessionStorage.isSupport()) {2090 try {2091 sessionStorage.setItem('sensorsdata_jssdk_debug', 'true');2092 } catch (e) {2093 sd.log('enableLocalLog error: ' + e.message);2094 }2095 }2096 };2097 sd.disableLocalLog = function() {2098 if (_.sessionStorage.isSupport()) {2099 sessionStorage.removeItem('sensorsdata_jssdk_debug');2100 }2101 };2102 sd.debug = {2103 distinct_id: function() {},2104 jssdkDebug: function() {},2105 _sendDebug: function(debugString) {2106 sd.track('_sensorsdata2019_debug', {2107 _jssdk_debug_info: debugString2108 });2109 },2110 apph5: function(obj) {2111 var name = 'app_h5打通失败-';2112 var relation = {2113 '1': name + 'use_app_track为false',2114 '2': name + 'Android或者iOS,没有暴露相应方法',2115 '3.1': name + 'Android校验server_url失败',2116 '3.2': name + 'iOS校验server_url失败',2117 '4.1': name + 'H5 校验 iOS server_url 失败',2118 '4.2': name + 'H5 校验 Android server_url 失败',2119 '4.3': name + 'H5 数据成功发往 Android',2120 '4.4': name + 'H5 数据成功发往 iOS'2121 };2122 var output = obj.output;2123 var step = obj.step;2124 var data = obj.data || '';2125 if (output === 'all' || output === 'console') {2126 sd.log(relation[step]);2127 }2128 if ((output === 'all' || output === 'code') && _.isObject(sd.para.is_debug) && sd.para.is_debug.apph5) {2129 if (!data.type || data.type.slice(0, 7) !== 'profile') {2130 data.properties._jssdk_debug_info = 'apph5-' + String(step);2131 }2132 }2133 },2134 defineMode: function(type){2135 var debugList = {2136 '1': {2137 "title": "当前页面无法进行可视化全埋点",2138 "message": "App SDK 与 Web SDK 没有进行打通,请联系贵方技术人员修正 App SDK 的配置,详细信息请查看文档。",2139 "link_text": "配置文档",2140 "link_url": "https://manual.sensorsdata.cn/sa/latest/app-h5-1573913.html"2141 },2142 '2': {2143 "title": "当前页面无法进行可视化全埋点",2144 "message": "App SDK 与 Web SDK 没有进行打通,请联系贵方技术人员修正 Web SDK 的配置,详细信息请查看文档。",2145 "link_text": "配置文档",2146 "link_url": "https://manual.sensorsdata.cn/sa/latest/app-h5-1573913.html"2147 },2148 '3': {2149 "title": "当前页面无法进行可视化全埋点",2150 "message": "Web SDK 没有开启全埋点配置,请联系贵方工作人员修正 SDK 的配置,详细信息请查看文档。",2151 "link_text": "配置文档",2152 "link_url": "https://manual.sensorsdata.cn/sa/latest/app-h5-1573913.html"2153 },2154 '4': {2155 "title": "当前页面无法进行可视化全埋点",2156 "message": "Web SDK 配置的数据校验地址与 App SDK 配置的数据校验地址不一致,请联系贵方工作人员修正 SDK 的配置,详细信息请查看文档。",2157 "link_text": "配置文档",2158 "link_url": "https://manual.sensorsdata.cn/sa/latest/app-h5-1573913.html"2159 }2160 };2161 if(type && debugList[type]){2162 return debugList[type];2163 }else{2164 return false;2165 }2166 }2167 };2168 var commonWays = {2169 setOnlineState: function(state) {2170 if (state === true && _.isObject(sd.para.jsapp) && typeof sd.para.jsapp.getData === 'function') {2171 sd.para.jsapp.isOnline = true;2172 var arr = sd.para.jsapp.getData();2173 if (_.isArray(arr) && arr.length > 0) {2174 _.each(arr, function(str) {2175 if (_.isJSONString(str)) {2176 sd.sendState.pushSend(JSON.parse(str));2177 }2178 });2179 }2180 } else {2181 sd.para.jsapp.isOnline = false;2182 }2183 },2184 autoTrackIsUsed: false,2185 isReady: function(callback) {2186 callback();2187 },2188 getUtm: function() {2189 return _.info.campaignParams();2190 },2191 getStayTime: function() {2192 return ((new Date()) - sd._t) / 1000;2193 },2194 setProfileLocal: function(obj) {2195 if (!_.localStorage.isSupport()) {2196 sd.setProfile(obj);2197 return false;2198 }2199 if (!_.isObject(obj) || _.isEmptyObject(obj)) {2200 return false;2201 }2202 var saveData = _.localStorage.parse('sensorsdata_2015_jssdk_profile');2203 var isNeedSend = false;2204 if (_.isObject(saveData) && !_.isEmptyObject(saveData)) {2205 for (var i in obj) {2206 if ((i in saveData && saveData[i] !== obj[i]) || !(i in saveData)) {2207 saveData[i] = obj[i];2208 isNeedSend = true;2209 }2210 }2211 if (isNeedSend) {2212 _.localStorage.set('sensorsdata_2015_jssdk_profile', JSON.stringify(saveData));2213 sd.setProfile(obj);2214 }2215 } else {2216 _.localStorage.set('sensorsdata_2015_jssdk_profile', JSON.stringify(obj));2217 sd.setProfile(obj);2218 }2219 },2220 setInitReferrer: function() {2221 var _referrer = _.getReferrer();2222 sd.setOnceProfile({2223 _init_referrer: _referrer,2224 _init_referrer_host: _.info.pageProp.referrer_host2225 });2226 },2227 setSessionReferrer: function() {2228 var _referrer = _.getReferrer();2229 store.setSessionPropsOnce({2230 _session_referrer: _referrer,2231 _session_referrer_host: _.info.pageProp.referrer_host2232 });2233 },2234 setDefaultAttr: function() {2235 _.info.register({2236 _current_url: location.href,2237 _referrer: _.getReferrer(),2238 _referring_host: _.info.pageProp.referrer_host2239 });2240 },2241 trackHeatMap: function(target, props, callback) {2242 if ((typeof target === 'object') && target.tagName) {2243 var tagName = target.tagName.toLowerCase();2244 var parent_ele = target.parentNode.tagName.toLowerCase();2245 if (tagName !== 'button' && tagName !== 'a' && parent_ele !== 'a' && parent_ele !== 'button' && tagName !== 'input' && tagName !== 'textarea' && !_.hasAttribute(target, 'data-sensors-click')) {2246 heatmap.start(null, target, tagName, props, callback);2247 }2248 }2249 },2250 trackAllHeatMap: function(target, props, callback) {2251 if ((typeof target === 'object') && target.tagName) {2252 var tagName = target.tagName.toLowerCase();2253 heatmap.start(null, target, tagName, props, callback);2254 }2255 },2256 autoTrackSinglePage: function(para, callback) {2257 if (this.autoTrackIsUsed) {2258 var url = _.info.pageProp.url;2259 } else {2260 var url = _.info.pageProp.referrer;2261 }2262 para = _.isObject(para) ? para : {};2263 para = _.isObject(para) ? para : {};2264 function getUtm() {2265 var utms = _.info.campaignParams();2266 var $utms = {};2267 for (var i in utms) {2268 if ((' ' + sd.source_channel_standard + ' ').indexOf(' ' + i + ' ') !== -1) {2269 $utms['$' + i] = utms[i];2270 } else {2271 $utms[i] = utms[i];2272 }2273 }2274 return $utms;2275 }2276 if (sd.is_first_visitor && !para.not_set_profile) {2277 sd.setOnceProfile(_.extend({2278 $first_visit_time: new Date(),2279 $first_referrer: _.getReferrer(),2280 $first_browser_language: navigator.language || '取值异常',2281 $first_browser_charset: typeof document.charset === 'string' ? document.charset.toUpperCase() : '取值异常',2282 $first_traffic_source_type: _.getSourceFromReferrer(),2283 $first_search_keyword: _.getKeywordFromReferrer()2284 }, getUtm()));2285 sd.is_first_visitor = false;2286 }2287 if (para.not_set_profile) {2288 delete para.not_set_profile;2289 }2290 function closure(p, c) {2291 sd.track('$pageview', _.extend({2292 $referrer: url,2293 $url: location.href,2294 $url_path: location.pathname,2295 $title: document.title2296 }, p, getUtm()), c);2297 url = location.href;2298 }2299 closure(para, callback);2300 this.autoTrackSinglePage = closure;2301 },2302 autoTrackWithoutProfile: function(para, callback) {2303 para = _.isObject(para) ? para : {};2304 this.autoTrack(_.extend(para, {2305 not_set_profile: true2306 }), callback);2307 },2308 autoTrack: function(para, callback) {2309 para = _.isObject(para) ? para : {};2310 var utms = _.info.campaignParams();2311 var $utms = {};2312 for (var i in utms) {2313 if ((' ' + sd.source_channel_standard + ' ').indexOf(' ' + i + ' ') !== -1) {2314 $utms['$' + i] = utms[i];2315 } else {2316 $utms[i] = utms[i];2317 }2318 }2319 if (sd.is_first_visitor && !para.not_set_profile) {2320 sd.setOnceProfile(_.extend({2321 $first_visit_time: new Date(),2322 $first_referrer: _.getReferrer(),2323 $first_browser_language: navigator.language || '取值异常',2324 $first_browser_charset: typeof document.charset === 'string' ? document.charset.toUpperCase() : '取值异常',2325 $first_traffic_source_type: _.getSourceFromReferrer(),2326 $first_search_keyword: _.getKeywordFromReferrer()2327 }, $utms));2328 sd.is_first_visitor = false;2329 }2330 if (para.not_set_profile) {2331 delete para.not_set_profile;2332 }2333 var current_page_url = location.href;2334 if (sd.para.is_single_page) {2335 _.addHashEvent(function() {2336 var referrer = _.getReferrer(current_page_url);2337 sd.track('$pageview', _.extend({2338 $referrer: referrer,2339 $url: location.href,2340 $url_path: location.pathname,2341 $title: document.title2342 }, $utms, para), callback);2343 current_page_url = location.href;2344 });2345 }2346 sd.track('$pageview', _.extend({2347 $referrer: _.getReferrer(),2348 $url: location.href,2349 $url_path: location.pathname,2350 $title: document.title2351 }, $utms, para), callback);2352 this.autoTrackIsUsed = true;2353 },2354 getAnonymousID: function() {2355 if (_.isEmptyObject(sd.store._state)) {2356 return '请先初始化SDK';2357 } else {2358 return sd.store._state._first_id || sd.store._state.first_id || sd.store._state._distinct_id || sd.store._state.distinct_id;2359 }2360 },2361 setPlugin: function(para) {2362 if (!_.isObject(para)) {2363 return false;2364 }2365 _.each(para, function(v, k) {2366 if (_.isFunction(v)) {2367 if (_.isObject(window.SensorsDataWebJSSDKPlugin) && window.SensorsDataWebJSSDKPlugin[k]) {2368 v(window.SensorsDataWebJSSDKPlugin[k]);2369 } else {2370 sd.log(k + '没有获取到,请查阅文档,调整' + k + '的引入顺序!')2371 }2372 }2373 });2374 }2375 };2376 sd.quick = function() {2377 var arg = Array.prototype.slice.call(arguments);2378 var arg0 = arg[0];2379 var arg1 = arg.slice(1);2380 if (typeof arg0 === 'string' && commonWays[arg0]) {2381 return commonWays[arg0].apply(commonWays, arg1);2382 } else if (typeof arg0 === 'function') {2383 arg0.apply(sd, arg1);2384 } else {2385 sd.log('quick方法中没有这个功能' + arg[0]);2386 }2387 };2388 sd.track = function(e, p, c) {2389 if (saEvent.check({2390 event: e,2391 properties: p2392 })) {2393 saEvent.send({2394 type: 'track',2395 event: e,2396 properties: p2397 }, c);2398 }2399 };2400 sd.trackLink = function(link, event_name, event_prop) {2401 if (typeof link === 'object' && link.tagName) {2402 _.trackLink({2403 ele: link2404 }, event_name, event_prop);2405 } else if (typeof link === 'object' && link.target && link.event) {2406 _.trackLink(link, event_name, event_prop);2407 }2408 };2409 sd.trackLinks = function(link, event_name, event_prop) {2410 var ele = link;2411 event_prop = event_prop || {};2412 if (!link || (typeof link !== 'object')) {2413 return false;2414 }2415 if (!link.href || /^javascript/.test(link.href) || link.target) {2416 return false;2417 }2418 _.addEvent(link, 'click', function(e) {2419 e.preventDefault();2420 var hasCalled = false;2421 setTimeout(track_a_click, 1000);2422 function track_a_click() {2423 if (!hasCalled) {2424 hasCalled = true;2425 location.href = link.href;2426 }2427 }2428 sd.track(event_name, event_prop, track_a_click);2429 });2430 };2431 sd.setProfile = function(p, c) {2432 if (saEvent.check({2433 propertiesMust: p2434 })) {2435 saEvent.send({2436 type: 'profile_set',2437 properties: p2438 }, c);2439 }2440 };2441 sd.setOnceProfile = function(p, c) {2442 if (saEvent.check({2443 propertiesMust: p2444 })) {2445 saEvent.send({2446 type: 'profile_set_once',2447 properties: p2448 }, c);2449 }2450 };2451 sd.appendProfile = function(p, c) {2452 if (saEvent.check({2453 propertiesMust: p2454 })) {2455 _.each(p, function(value, key) {2456 if (_.isString(value)) {2457 p[key] = [value];2458 } else if (_.isArray(value)) {2459 p[key] = value;2460 } else {2461 delete p[key];2462 sd.log('appendProfile属性的值必须是字符串或者数组');2463 }2464 });2465 if (!_.isEmptyObject(p)) {2466 saEvent.send({2467 type: 'profile_append',2468 properties: p2469 }, c);2470 }2471 }2472 };2473 sd.incrementProfile = function(p, c) {2474 var str = p;2475 if (_.isString(p)) {2476 p = {}2477 p[str] = 1;2478 }2479 function isChecked(p) {2480 for (var i in p) {2481 if (!/-*\d+/.test(String(p[i]))) {2482 return false;2483 }2484 }2485 return true;2486 }2487 if (saEvent.check({2488 propertiesMust: p2489 })) {2490 if (isChecked(p)) {2491 saEvent.send({2492 type: 'profile_increment',2493 properties: p2494 }, c);2495 } else {2496 sd.log('profile_increment的值只能是数字');2497 }2498 }2499 };2500 sd.deleteProfile = function(c) {2501 saEvent.send({2502 type: 'profile_delete'2503 }, c);2504 store.set('distinct_id', _.UUID());2505 store.set('first_id', '');2506 };2507 sd.unsetProfile = function(p, c) {2508 var str = p;2509 var temp = {};2510 if (_.isString(p)) {2511 p = [];2512 p.push(str);2513 }2514 if (_.isArray(p)) {2515 _.each(p, function(v) {2516 if (_.isString(v)) {2517 temp[v] = true;2518 } else {2519 sd.log('profile_unset给的数组里面的值必须时string,已经过滤掉', v);2520 }2521 });2522 saEvent.send({2523 type: 'profile_unset',2524 properties: temp2525 }, c);2526 } else {2527 sd.log('profile_unset的参数是数组');2528 }2529 };2530 sd.identify = function(id, isSave) {2531 if (typeof id === 'number') {2532 id = String(id);2533 }2534 var firstId = store.getFirstId();2535 if (typeof id === 'undefined') {2536 var uuid = _.UUID();2537 if (firstId) {2538 store.set('first_id', uuid);2539 } else {2540 store.set('distinct_id', uuid);2541 }2542 } else if (saEvent.check({2543 distinct_id: id2544 })) {2545 if (isSave === true) {2546 if (firstId) {2547 store.set('first_id', id);2548 } else {2549 store.set('distinct_id', id);2550 }2551 } else {2552 if (firstId) {2553 store.change('first_id', id);2554 } else {2555 store.change('distinct_id', id);2556 }2557 }2558 } else {2559 sd.log('identify的参数必须是字符串');2560 }2561 };2562 sd.trackSignup = function(id, e, p, c) {2563 if (saEvent.check({2564 distinct_id: id,2565 event: e,2566 properties: p2567 })) {2568 var original_id = store.getFirstId() || store.getDistinctId();2569 store.set('distinct_id', id);2570 saEvent.send({2571 original_id: original_id,2572 distinct_id: id,2573 type: 'track_signup',2574 event: e,2575 properties: p2576 }, c);2577 }2578 };2579 sd.trackAbtest = function(t, g) {};2580 sd.registerPage = function(obj) {2581 if (saEvent.check({2582 properties: obj2583 })) {2584 _.extend(_.info.currentProps, obj);2585 } else {2586 sd.log('register输入的参数有误');2587 }2588 };2589 sd.clearAllRegister = function(arr) {2590 store.clearAllProps(arr);2591 };2592 sd.register = function(props) {2593 if (saEvent.check({2594 properties: props2595 })) {2596 store.setProps(props);2597 } else {2598 sd.log('register输入的参数有误');2599 }2600 };2601 sd.registerOnce = function(props) {2602 if (saEvent.check({2603 properties: props2604 })) {2605 store.setPropsOnce(props);2606 } else {2607 sd.log('registerOnce输入的参数有误');2608 }2609 };2610 sd.registerSession = function(props) {2611 if (saEvent.check({2612 properties: props2613 })) {2614 store.setSessionProps(props);2615 } else {2616 sd.log('registerSession输入的参数有误');2617 }2618 };2619 sd.registerSessionOnce = function(props) {2620 if (saEvent.check({2621 properties: props2622 })) {2623 store.setSessionPropsOnce(props);2624 } else {2625 sd.log('registerSessionOnce输入的参数有误');2626 }2627 };2628 sd.login = function(id, callback) {2629 if (typeof id === 'number') {2630 id = String(id);2631 }2632 if (saEvent.check({2633 distinct_id: id2634 })) {2635 var firstId = store.getFirstId();2636 var distinctId = store.getDistinctId();2637 if (id !== distinctId) {2638 if (!firstId) {2639 store.set('first_id', distinctId);2640 }2641 sd.trackSignup(id, '$SignUp', {}, callback);2642 } else {2643 callback && callback();2644 }2645 } else {2646 sd.log('login的参数必须是字符串');2647 callback && callback();2648 }2649 };2650 sd.logout = function(isChangeId) {2651 var firstId = store.getFirstId();2652 if (firstId) {2653 store.set('first_id', '');2654 if (isChangeId === true) {2655 var uuid = _.UUID();2656 store.set('distinct_id', uuid);2657 } else {2658 store.set('distinct_id', firstId);2659 }2660 } else {2661 sd.log('没有first_id,logout失败');2662 }2663 };2664 sd.getPresetProperties = function() {2665 function getUtm() {2666 var utms = _.info.campaignParams();2667 var $utms = {};2668 for (var i in utms) {2669 if ((' ' + sd.source_channel_standard + ' ').indexOf(' ' + i + ' ') !== -1) {2670 $utms['$' + i] = utms[i];2671 } else {2672 $utms[i] = utms[i];2673 }2674 }2675 return $utms;2676 }2677 var obj = {2678 $referrer: _.info.pageProp.referrer || '',2679 $referrer_host: _.info.pageProp.referrer ? _.getHostname(_.info.pageProp.referrer) : '',2680 $url: location.href,2681 $url_path: location.pathname,2682 $title: document.title || '',2683 _distinct_id: store.getDistinctId()2684 };2685 var result = _.extend({}, _.info.properties(), sd.store.getProps(), getUtm(), obj);2686 if (sd.para.preset_properties.latest_referrer && sd.para.preset_properties.latest_referrer_host) {2687 result.$latest_referrer_host = result.$latest_referrer === "" ? "" : _.getHostname(result.$latest_referrer);2688 }2689 return result;2690 };2691 function BatchSend() {2692 this.sendingData = 0;2693 };2694 BatchSend.prototype = {2695 add: function(data) {2696 if (_.isObject(data)) {2697 this.writeStore(data);2698 if (data.type === 'track_signup' || data.event === '$pageview') {2699 this.sendStrategy();2700 }2701 }2702 },2703 remove: function(keys) {2704 var me = this;2705 if (this.sendingData > 0) {2706 --this.sendingData;2707 }2708 if (_.isArray(keys) && keys.length > 0) {2709 _.each(keys, function(key) {2710 _.localStorage.remove(key);2711 });2712 }2713 },2714 send: function(data) {2715 var me = this;2716 var server_url = _.isArray(sd.para.server_url) ? sd.para.server_url[0] : sd.para.server_url;2717 _.ajax({2718 url: server_url,2719 type: 'POST',2720 data: 'data_list=' + encodeURIComponent(_.base64Encode(JSON.stringify(data.vals))),2721 credentials: false,2722 timeout: sd.para.batch_send.datasend_timeout,2723 cors: true,2724 success: function() {2725 me.remove(data.keys);2726 },2727 error: function() {2728 if (me.sendingData > 0) {2729 --me.sendingData;2730 }2731 }2732 });2733 },2734 sendPrepare: function(data) {2735 var arr = data.vals;2736 var maxLen = sd.para.batch_send.one_send_max_length;2737 var arrLen = arr.length;2738 if (arrLen > 0) {2739 if (arrLen <= maxLen) {2740 this.send({2741 keys: data.keys,2742 vals: arr2743 });2744 } else {2745 for (var i = 0; i * maxLen < arrLen; i++) {2746 this.send({2747 keys: data.keys.splice(0, maxLen),2748 vals: arr.splice(0, maxLen)2749 });2750 }2751 }2752 }2753 },2754 sendStrategy: function() {2755 var data = this.readStore();2756 if (data.keys.length > 0 && this.sendingData === 0) {2757 this.sendingData = Math.ceil(data.vals.length / sd.para.batch_send.one_send_max_length)2758 this.sendPrepare(data);2759 }2760 },2761 batchInterval: function() {2762 var me = this;2763 setInterval(function() {2764 me.sendStrategy();2765 }, sd.para.batch_send.send_interval);2766 },2767 readStore: function() {2768 var keys = [];2769 var vals = [];2770 var obj = {};2771 var val = null;2772 var now = (new Date()).getTime();2773 var len = localStorage.length;2774 for (var i = 0; i < len; i++) {2775 var key = localStorage.key(i);2776 if (key.indexOf('sawebjssdk-') === 0 && /^sawebjssdk\-\d+$/.test(key)) {2777 val = localStorage.getItem(key);2778 if (val) {2779 val = _.safeJSONParse(val);2780 if (val && _.isObject(val)) {2781 val._flush_time = now;2782 keys.push(key);2783 vals.push(val);2784 } else {2785 localStorage.removeItem(key);2786 sd.log('localStorage-数据parse异常' + val);2787 }2788 } else {2789 localStorage.removeItem(key);2790 sd.log('localStorage-数据取值异常' + val);2791 }2792 }2793 }2794 return {2795 keys: keys,2796 vals: vals2797 };2798 },2799 writeStore: function(data) {2800 var uuid = String(Math.random()).slice(2, 5) + String(Math.random()).slice(2, 5) + String((new Date()).getTime()).slice(3);2801 localStorage.setItem('sawebjssdk-' + uuid, JSON.stringify(data));2802 }2803 };2804 sd.batchSend = new BatchSend();2805 var dataSend = {};2806 dataSend.getSendUrl = function(url, data) {2807 var base64Data = _.base64Encode(data);2808 var crc = 'crc=' + _.hashCode(base64Data);2809 if (url.indexOf('?') !== -1) {2810 return url + '&data=' + encodeURIComponent(base64Data) + '&ext=' + encodeURIComponent(crc);2811 } else {2812 return url + '?data=' + encodeURIComponent(base64Data) + '&ext=' + encodeURIComponent(crc);2813 }2814 };2815 dataSend.getSendData = function(data) {2816 var base64Data = _.base64Encode(data);2817 var crc = 'crc=' + _.hashCode(base64Data);2818 return 'data=' + encodeURIComponent(base64Data) + '&ext=' + encodeURIComponent(crc);2819 };2820 dataSend.getInstance = function(data) {2821 var sendType = this.getSendType(data);2822 var obj = new this[sendType](data);2823 var start = obj.start;2824 obj.start = function() {2825 if (_.isObject(sd.para.is_debug) && sd.para.is_debug.storage && sd.store.requests) {2826 sd.store.requests.push({2827 name: this.server_url,2828 initiatorType: this.img ? 'img' : 'xmlhttprequest',2829 entryType: "resource",2830 requestData: this.data2831 });2832 }2833 var me = this;2834 start.apply(this, arguments);2835 setTimeout(function() {2836 me.isEnd(true);2837 }, sd.para.callback_timeout);2838 };2839 obj.end = function() {2840 this.callback && this.callback();2841 var self = this;2842 setTimeout(function() {2843 self.lastClear && self.lastClear();2844 }, sd.para.datasend_timeout - sd.para.callback_timeout);2845 };2846 obj.isEnd = function(isDelay) {2847 if (!this.received) {2848 this.received = true;2849 this.end();2850 var self = this;2851 if (isDelay) {2852 if (sd.para.queue_timeout - sd.para.callback_timeout <= 0) {2853 self.close();2854 } else {2855 setTimeout(function() {2856 self.close();2857 }, sd.para.queue_timeout - sd.para.callback_timeout);2858 }2859 } else {2860 self.close();2861 }2862 }2863 };2864 return obj;2865 };2866 dataSend.getSendType = function(data) {2867 var supportedSendTypes = ['image', 'ajax', 'beacon'];2868 var sendType = supportedSendTypes[0];2869 if (data.config && _.indexOf(supportedSendTypes, data.config.send_type) > -1) {2870 sendType = data.config.send_type;2871 } else {2872 sendType = sd.para.send_type;2873 }2874 if (sendType === 'beacon' && typeof navigator.sendBeacon !== "function") {2875 sendType = 'image';2876 }2877 if (sendType === 'ajax' && _.isSupportCors() === false) {2878 sendType = 'image';2879 }2880 return sendType;2881 };2882 dataSend.image = function(para) {2883 this.callback = para.callback;2884 this.img = document.createElement('img');2885 this.img.width = 1;2886 this.img.height = 1;2887 if (sd.para.img_use_crossorigin) {2888 this.img.crossOrigin = 'anonymous';2889 }2890 this.data = para.data;2891 this.server_url = dataSend.getSendUrl(para.server_url, para.data);2892 };2893 dataSend.image.prototype.start = function() {2894 var me = this;2895 if (sd.para.ignore_oom) {2896 this.img.onload = function() {2897 this.onload = null;2898 this.onerror = null;2899 this.onabort = null;2900 me.isEnd();2901 };2902 this.img.onerror = function() {2903 this.onload = null;2904 this.onerror = null;2905 this.onabort = null;2906 me.isEnd();2907 };2908 this.img.onabort = function() {2909 this.onload = null;2910 this.onerror = null;2911 this.onabort = null;2912 me.isEnd();2913 };2914 }2915 this.img.src = this.server_url;2916 };2917 dataSend.image.prototype.lastClear = function() {2918 this.img.src = "";2919 }2920 dataSend.ajax = function(para) {2921 this.callback = para.callback;2922 this.server_url = para.server_url;2923 this.data = dataSend.getSendData(para.data);2924 };2925 dataSend.ajax.prototype.start = function() {2926 var me = this;2927 _.ajax({2928 url: this.server_url,2929 type: 'POST',2930 data: this.data,2931 credentials: false,2932 timeout: sd.para.datasend_timeout,2933 cors: true,2934 success: function() {2935 me.isEnd();2936 },2937 error: function() {2938 me.isEnd();2939 }2940 });2941 };2942 dataSend.beacon = function(para) {2943 this.callback = para.callback;2944 this.server_url = para.server_url;2945 this.data = dataSend.getSendData(para.data);2946 };2947 dataSend.beacon.prototype.start = function() {2948 var me = this;2949 if (typeof navigator === 'object' && typeof navigator.sendBeacon === 'function') {2950 navigator.sendBeacon(this.server_url, this.data);2951 }2952 setTimeout(function() {2953 me.isEnd();2954 }, 40);2955 };2956 var sendState = {};2957 sd.sendState = sendState;2958 sd.events = new _.eventEmitter();2959 sendState.queue = _.autoExeQueue();2960 sendState.requestData = null;2961 sendState.getSendCall = function(data, config, callback) {2962 if (sd.is_heatmap_render_mode) {2963 return false;2964 }2965 if (sd.readyState.state < 3) {2966 sd.log('初始化没有完成');2967 return false;2968 }2969 data._track_id = Number(String(Math.random()).slice(2, 5) + String(Math.random()).slice(2, 4) + String((new Date()).getTime()).slice(-4));2970 if (sd.para.use_client_time) {2971 data._flush_time = (new Date()).getTime();2972 }2973 var originData = data;2974 data = JSON.stringify(data);2975 this.requestData = {2976 data: originData,2977 config: config,2978 callback: callback2979 };2980 sd.events.tempAdd('send', originData);2981 if (!sd.para.app_js_bridge && sd.para.batch_send && localStorage.length < 200) {2982 sd.log(originData);2983 sd.batchSend.add(this.requestData.data);2984 return false;2985 }2986 if (_.isObject(sd.para.app_js_bridge) || sd.para.app_js_bridge === 'only') {2987 if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.sensorsdataNativeTracker && _.isObject(window.SensorsData_iOS_JS_Bridge) && window.SensorsData_iOS_JS_Bridge.sensorsdata_app_server_url) {2988 if (sd.para.app_js_bridge.H5verify) {2989 sd.debug.apph5({2990 data: originData,2991 step: '4.4',2992 output: 'all'2993 });2994 window.webkit.messageHandlers.sensorsdataNativeTracker.postMessage(JSON.stringify({2995 callType: 'app_h5_track',2996 data: _.extend({2997 server_url: sd.para.server_url2998 }, originData)2999 }));3000 } else {3001 if (sd.para.app_js_bridge.is_send) {3002 sd.debug.apph5({3003 data: originData,3004 step: '4.1',3005 output: 'all'3006 });3007 this.prepareServerUrl();3008 }3009 }3010 } else if (_.isObject(window.SensorsData_APP_New_H5_Bridge) && window.SensorsData_APP_New_H5_Bridge.sensorsdata_get_server_url && window.SensorsData_APP_New_H5_Bridge.sensorsdata_track) {3011 if (sd.para.app_js_bridge.H5verify) {3012 sd.debug.apph5({3013 data: originData,3014 step: '4.3',3015 output: 'all'3016 });3017 SensorsData_APP_New_H5_Bridge.sensorsdata_track(JSON.stringify(_.extend({3018 server_url: sd.para.server_url3019 }, originData)));3020 } else {3021 if (sd.para.app_js_bridge.is_send) {3022 sd.debug.apph5({3023 data: originData,3024 step: '4.2',3025 output: 'all'3026 });3027 this.prepareServerUrl();3028 }3029 }3030 } else if ((typeof SensorsData_APP_JS_Bridge === 'object') && (SensorsData_APP_JS_Bridge.sensorsdata_verify || SensorsData_APP_JS_Bridge.sensorsdata_track)) {3031 if (SensorsData_APP_JS_Bridge.sensorsdata_verify) {3032 if (!SensorsData_APP_JS_Bridge.sensorsdata_verify(JSON.stringify(_.extend({3033 server_url: sd.para.server_url3034 }, originData)))) {3035 if (sd.para.app_js_bridge.is_send) {3036 sd.debug.apph5({3037 data: originData,3038 step: '3.1',3039 output: 'all'3040 });3041 this.prepareServerUrl();3042 }3043 } else {3044 (typeof callback === 'function') && callback();3045 }3046 } else {3047 SensorsData_APP_JS_Bridge.sensorsdata_track(JSON.stringify(_.extend({3048 server_url: sd.para.server_url3049 }, originData)));3050 (typeof callback === 'function') && callback();3051 }3052 } else if ((/sensors-verify/.test(navigator.userAgent) || /sa-sdk-ios/.test(navigator.userAgent)) && !window.MSStream) {3053 var iframe = null;3054 if (/sensors-verify/.test(navigator.userAgent)) {3055 var match = navigator.userAgent.match(/sensors-verify\/([^\s]+)/);3056 if (match && match[0] && (typeof match[1] === 'string') && (match[1].split('?').length === 2)) {3057 match = match[1].split('?');3058 var hostname = null;3059 var project = null;3060 try {3061 hostname = _.URL(sd.para.server_url).hostname;3062 project = _.URL(sd.para.server_url).searchParams.get('project') || 'default';3063 } catch (e) {3064 sd.log(e);3065 };3066 if (hostname && hostname === match[0] && project && project === match[1]) {3067 iframe = document.createElement('iframe');3068 iframe.setAttribute('src', 'sensorsanalytics://trackEvent?event=' + encodeURIComponent(JSON.stringify(_.extend({3069 server_url: sd.para.server_url3070 }, originData))));3071 document.documentElement.appendChild(iframe);3072 iframe.parentNode.removeChild(iframe);3073 iframe = null;3074 (typeof callback === 'function') && callback();3075 } else {3076 if (sd.para.app_js_bridge.is_send) {3077 sd.debug.apph5({3078 data: originData,3079 step: '3.2',3080 output: 'all'3081 });3082 this.prepareServerUrl();3083 }3084 }3085 }3086 } else {3087 iframe = document.createElement('iframe');3088 iframe.setAttribute('src', 'sensorsanalytics://trackEvent?event=' + encodeURIComponent(JSON.stringify(_.extend({3089 server_url: sd.para.server_url3090 }, originData))));3091 document.documentElement.appendChild(iframe);3092 iframe.parentNode.removeChild(iframe);3093 iframe = null;3094 (typeof callback === 'function') && callback();3095 }3096 } else {3097 if (_.isObject(sd.para.app_js_bridge) && sd.para.app_js_bridge.is_send === true) {3098 sd.debug.apph5({3099 data: originData,3100 step: '2',3101 output: 'all'3102 });3103 this.prepareServerUrl();3104 }3105 }3106 } else if (sd.para.app_js_bridge === 'mui') {3107 if (_.isObject(window.plus) && window.plus.SDAnalytics && window.plus.SDAnalytics.trackH5Event) {3108 window.plus.SDAnalytics.trackH5Event(data);3109 }3110 } else {3111 sd.debug.apph5({3112 data: originData,3113 step: '1',3114 output: 'code'3115 });3116 this.prepareServerUrl();3117 }3118 sd.log(originData);3119 };3120 sendState.prepareServerUrl = function() {3121 if (typeof this.requestData.config === 'object' && this.requestData.config.server_url) {3122 this.sendCall(this.requestData.config.server_url, this.requestData.callback);3123 } else if (_.isArray(sd.para.server_url)) {3124 for (var i = 0; i < sd.para.server_url.length; i++) {3125 this.sendCall(sd.para.server_url[i]);3126 }3127 } else {3128 this.sendCall(sd.para.server_url, this.requestData.callback);3129 }3130 };3131 sendState.sendCall = function(server_url, callback) {3132 var data = {3133 server_url: server_url,3134 data: JSON.stringify(this.requestData.data),3135 callback: callback,3136 config: this.requestData.config3137 };3138 if (_.isObject(sd.para.jsapp) && !sd.para.jsapp.isOnline && typeof sd.para.jsapp.setData === 'function') {3139 delete data.callback;3140 data = JSON.stringify(data);3141 sd.para.jsapp.setData(data);3142 } else {3143 this.pushSend(data);3144 }3145 };3146 sendState.pushSend = function(data) {3147 var instance = dataSend.getInstance(data);3148 var me = this;3149 instance.close = function() {3150 me.queue.close();3151 };3152 this.queue.enqueue(instance);3153 };3154 var saEvent = {};3155 saEvent.checkOption = {3156 regChecks: {3157 regName: /^((?!^distinct_id$|^original_id$|^time$|^properties$|^id$|^first_id$|^second_id$|^users$|^events$|^event$|^user_id$|^date$|^datetime$)[a-zA-Z_$][a-zA-Z\d_$]{0,99})$/i3158 },3159 checkPropertiesKey: function(obj) {3160 var me = this,3161 flag = true;3162 _.each(obj, function(content, key) {3163 if (!me.regChecks.regName.test(key)) {3164 flag = false;3165 }3166 });3167 return flag;3168 },3169 check: function(a, b) {3170 if (typeof this[a] === 'string') {3171 return this[this[a]](b);3172 } else {3173 return this[a](b);3174 }3175 },3176 str: function(s) {3177 if (!_.isString(s)) {3178 sd.log('请检查参数格式,必须是字符串');3179 return true;3180 } else {3181 return true;3182 }3183 },3184 properties: function(p) {3185 _.strip_sa_properties(p);3186 if (p) {3187 if (_.isObject(p)) {3188 if (this.checkPropertiesKey(p)) {3189 return true;3190 } else {3191 sd.log('properties 里的自定义属性名需要是合法的变量名,不能以数字开头,且只包含:大小写字母、数字、下划线,自定义属性不能以 $ 开头');3192 return true;3193 }3194 } else {3195 sd.log('properties可以没有,但有的话必须是对象');3196 return true;3197 }3198 } else {3199 return true;3200 }3201 },3202 propertiesMust: function(p) {3203 _.strip_sa_properties(p);3204 if (p === undefined || !_.isObject(p) || _.isEmptyObject(p)) {3205 sd.log('properties必须是对象且有值');3206 return true;3207 } else {3208 if (this.checkPropertiesKey(p)) {3209 return true;3210 } else {3211 sd.log('properties 里的自定义属性名需要是合法的变量名,不能以数字开头,且只包含:大小写字母、数字、下划线,自定义属性不能以 $ 开头');3212 return true;3213 }3214 }3215 },3216 event: function(s) {3217 if (!_.isString(s) || !this['regChecks']['regName'].test(s)) {3218 sd.log('请检查参数格式,eventName 必须是字符串,且需是合法的变量名,即不能以数字开头,且只包含:大小写字母、数字、下划线和 $,其中以 $ 开头的表明是系统的保留字段,自定义事件名请不要以 $ 开头');3219 return true;3220 } else {3221 return true;3222 }3223 },3224 test_id: 'str',3225 group_id: 'str',3226 distinct_id: function(id) {3227 if (_.isString(id) && /^.{1,255}$/.test(id)) {3228 return true;3229 } else {3230 sd.log('distinct_id必须是不能为空,且小于255位的字符串');3231 return false;3232 }3233 }3234 };3235 saEvent.check = function(p) {3236 var flag = true;3237 for (var i in p) {3238 if (!this.checkOption.check(i, p[i])) {3239 return false;3240 }3241 }3242 return flag;3243 };3244 saEvent.send = function(p, callback) {3245 var data = {3246 distinct_id: store.getDistinctId(),3247 lib: {3248 $lib: 'js',3249 $lib_method: 'code',3250 $lib_version: String(sd.lib_version)3251 },3252 properties: {}3253 };3254 if (_.isObject(p) && _.isObject(p.properties) && !_.isEmptyObject(p.properties) && p.properties.$lib_detail) {3255 data.lib.$lib_detail = p.properties.$lib_detail;3256 delete p.properties.$lib_detail;3257 }3258 _.extend(data, sd.store.getUnionId(), p);3259 if (_.isObject(p.properties) && !_.isEmptyObject(p.properties)) {3260 _.extend(data.properties, p.properties);3261 }3262 if (!p.type || p.type.slice(0, 7) !== 'profile') {3263 data.properties = _.extend({}, _.info.properties(), store.getProps(), store.getSessionProps(), _.info.currentProps, data.properties);3264 if (sd.para.preset_properties.latest_referrer && !_.isString(data.properties.$latest_referrer)) {3265 data.properties.$latest_referrer = '取值异常';3266 }3267 if (sd.para.preset_properties.latest_search_keyword && !_.isString(data.properties.$latest_search_keyword)) {3268 data.properties.$latest_search_keyword = '取值异常';3269 }3270 if (sd.para.preset_properties.latest_traffic_source_type && !_.isString(data.properties.$latest_traffic_source_type)) {3271 data.properties.$latest_traffic_source_type = '取值异常';3272 }3273 if (sd.para.preset_properties.latest_landing_page && !_.isString(data.properties.$latest_landing_page)) {3274 data.properties.$latest_landing_page = '取值异常';3275 }3276 }3277 if (data.properties.$time && _.isDate(data.properties.$time)) {3278 data.time = data.properties.$time * 1;3279 delete data.properties.$time;3280 } else {3281 if (sd.para.use_client_time) {3282 data.time = (new Date()) * 1;3283 }3284 }3285 _.parseSuperProperties(data.properties);3286 _.filterReservedProperties(data.properties);3287 _.searchObjDate(data);3288 _.searchObjString(data);3289 _.searchZZAppStyle(data);3290 var data_config = _.searchConfigData(data.properties);3291 saNewUser.checkIsAddSign(data);3292 saNewUser.checkIsFirstTime(data);3293 sd.addReferrerHost(data);3294 sd.addPropsHook(data);3295 if (sd.para.debug_mode === true) {3296 sd.log(data);3297 this.debugPath(JSON.stringify(data), callback);3298 } else {3299 sd.sendState.getSendCall(data, data_config, callback);3300 }3301 };3302 saEvent.debugPath = function(data, callback) {3303 var _data = data;3304 var url = '';3305 if (sd.para.debug_mode_url.indexOf('?') !== -1) {3306 url = sd.para.debug_mode_url + '&data=' + encodeURIComponent(_.base64Encode(data));3307 } else {3308 url = sd.para.debug_mode_url + '?data=' + encodeURIComponent(_.base64Encode(data));3309 }3310 _.ajax({3311 url: url,3312 type: 'GET',3313 cors: true,3314 header: {3315 'Dry-Run': String(sd.para.debug_mode_upload)3316 },3317 success: function(data) {3318 _.isEmptyObject(data) === true ? alert('debug数据发送成功' + _data) : alert('debug失败 错误原因' + JSON.stringify(data));3319 }3320 });3321 };3322 var store = sd.store = {3323 requests: [],3324 _sessionState: {},3325 _state: {3326 distinct_id: '',3327 first_id: '',3328 props: {}3329 },3330 getProps: function() {3331 return this._state.props || {};3332 },3333 getSessionProps: function() {3334 return this._sessionState;3335 },3336 getDistinctId: function() {3337 return this._state._distinct_id || this._state.distinct_id;3338 },3339 getUnionId: function() {3340 var obj = {};3341 var firstId = this._state._first_id || this._state.first_id,3342 distinct_id = this._state._distinct_id || this._state.distinct_id;3343 if (firstId && distinct_id) {3344 obj.login_id = distinct_id;3345 obj.anonymous_id = firstId;3346 } else {3347 obj.anonymous_id = distinct_id;3348 }3349 return obj;3350 },3351 getFirstId: function() {3352 return this._state._first_id || this._state.first_id;3353 },3354 toState: function(ds) {3355 var state = null;3356 if (ds != null && _.isJSONString(ds)) {3357 state = JSON.parse(ds);3358 this._state = _.extend(state);3359 if (state.distinct_id) {3360 if (typeof(state.props) === 'object') {3361 for (var key in state.props) {3362 if (typeof state.props[key] === 'string') {3363 state.props[key] = state.props[key].slice(0, sd.para.max_referrer_string_length);3364 }3365 }3366 this.save();3367 }3368 } else {3369 this.set('distinct_id', _.UUID());3370 sd.debug.distinct_id('1', ds);3371 }3372 } else {3373 this.set('distinct_id', _.UUID());3374 sd.debug.distinct_id('2', ds);3375 }3376 },3377 initSessionState: function() {3378 var ds = _.cookie.get('sensorsdata2015session');3379 var state = null;3380 if (ds !== null && (typeof(state = JSON.parse(ds)) === 'object')) {3381 this._sessionState = state || {};3382 }3383 },3384 setOnce: function(a, b) {3385 if (!(a in this._state)) {3386 this.set(a, b);3387 }3388 },3389 set: function(name, value) {3390 this._state = this._state || {};3391 if (name === 'distinct_id' && this._state.distinct_id) {3392 sd.events.tempAdd('changeDistinctId', value);3393 }3394 this._state[name] = value;3395 if (name === 'first_id') {3396 delete this._state._first_id;3397 } else if (name === 'distinct_id') {3398 delete this._state._distinct_id;3399 }3400 this.save();3401 },3402 change: function(name, value) {3403 this._state['_' + name] = value;3404 },3405 setSessionProps: function(newp) {3406 var props = this._sessionState;3407 _.extend(props, newp);3408 this.sessionSave(props);3409 },3410 setSessionPropsOnce: function(newp) {3411 var props = this._sessionState;3412 _.coverExtend(props, newp);3413 this.sessionSave(props);3414 },3415 setProps: function(newp, isCover) {3416 var props = {};3417 if (!isCover) {3418 props = _.extend((this._state.props || {}), newp);3419 } else {3420 props = newp;3421 }3422 for (var key in props) {3423 if (typeof props[key] === 'string') {3424 props[key] = props[key].slice(0, sd.para.max_referrer_string_length);3425 }3426 }3427 this.set('props', props);3428 },3429 setPropsOnce: function(newp) {3430 var props = this._state.props || {};3431 _.coverExtend(props, newp);3432 this.set('props', props);3433 },3434 clearAllProps: function(arr) {3435 this._sessionState = {};3436 if (_.isArray(arr) && arr.length > 0) {3437 for (var i = 0; i < arr.length; i++) {3438 if (_.isString(arr[i]) && arr[i].indexOf('latest_') === -1 && arr[i] in this._state.props) {3439 delete this._state.props[arr[i]];3440 }3441 }3442 } else {3443 for (var i in this._state.props) {3444 if (i.indexOf('latest_') !== 1) {3445 delete this._state.props[i];3446 }3447 }3448 }3449 this.sessionSave({});3450 this.save();3451 },3452 sessionSave: function(props) {3453 this._sessionState = props;3454 _.cookie.set('sensorsdata2015session', JSON.stringify(this._sessionState), 0);3455 },3456 save: function() {3457 var copyState = JSON.parse(JSON.stringify(this._state));3458 delete copyState._first_id;3459 delete copyState._distinct_id;3460 _.cookie.set(this.getCookieName(), JSON.stringify(copyState), 73000, sd.para.cross_subdomain);3461 },3462 getCookieName: function() {3463 var sub = '';3464 if (sd.para.cross_subdomain === false) {3465 try {3466 sub = _.URL(location.href).hostname;3467 } catch (e) {3468 sd.log(e);3469 }3470 if (typeof sub === 'string' && sub !== '') {3471 sub = 'sa_jssdk_2015_' + sub.replace(/\./g, '_');3472 } else {3473 sub = 'sa_jssdk_2015_root';3474 }3475 } else {3476 sub = 'sensorsdata2015jssdkcross';3477 }3478 return sub;3479 },3480 init: function() {3481 this.initSessionState();3482 var uuid = _.UUID();3483 var cross = _.cookie.get(this.getCookieName());3484 if (cross === null) {3485 sd.is_first_visitor = true;3486 this.set('distinct_id', uuid);3487 } else {3488 if (!_.isJSONString(cross) || !(JSON.parse(cross)).distinct_id) {3489 sd.is_first_visitor = true;3490 }3491 this.toState(cross);3492 }3493 saNewUser.setDeviceId(uuid);3494 saNewUser.storeInitCheck();3495 saNewUser.checkIsFirstLatest();3496 }3497 };3498 var saNewUser = {3499 checkIsAddSign: function(data) {3500 if (data.type === 'track') {3501 if (_.cookie.getNewUser()) {3502 data.properties.$is_first_day = true;3503 } else {3504 data.properties.$is_first_day = false;3505 }3506 }3507 },3508 is_first_visit_time: false,3509 checkIsFirstTime: function(data) {3510 if (data.type === 'track' && data.event === '$pageview') {3511 if (this.is_first_visit_time) {3512 data.properties.$is_first_time = true;3513 this.is_first_visit_time = false;3514 } else {3515 data.properties.$is_first_time = false;3516 }3517 }3518 },3519 setDeviceId: function(uuid) {3520 var device_id = null;3521 var ds = _.cookie.get('sensorsdata2015jssdkcross');3522 var state = {};3523 if (ds != null && _.isJSONString(ds)) {3524 state = JSON.parse(ds);3525 if (state.$device_id) {3526 device_id = state.$device_id;3527 }3528 }3529 device_id = device_id || uuid;3530 if (sd.para.cross_subdomain === true) {3531 store.set('$device_id', device_id);3532 } else {3533 state.$device_id = device_id;3534 _.cookie.set('sensorsdata2015jssdkcross', JSON.stringify(state), null, true);3535 }3536 if (sd.para.is_track_device_id) {3537 _.info.currentProps.$device_id = device_id;3538 }3539 },3540 storeInitCheck: function() {3541 if (sd.is_first_visitor) {3542 var date = new Date();3543 var obj = {3544 h: 23 - date.getHours(),3545 m: 59 - date.getMinutes(),3546 s: 59 - date.getSeconds()3547 };3548 _.cookie.set(_.cookie.getCookieName('new_user'), '1', obj.h * 3600 + obj.m * 60 + obj.s + 's');3549 this.is_first_visit_time = true;3550 } else {3551 if (!_.cookie.getNewUser()) {3552 this.checkIsAddSign = function(data) {3553 if (data.type === 'track') {3554 data.properties.$is_first_day = false;3555 }3556 };3557 }3558 this.checkIsFirstTime = function(data) {3559 if (data.type === 'track' && data.event === '$pageview') {3560 data.properties.$is_first_time = false;3561 }3562 }3563 }3564 },3565 checkIsFirstLatest: function() {3566 var url_domain = _.info.pageProp.url_domain;3567 var latest_utms = ['$utm_source', '$utm_medium', '$utm_campaign', '$utm_content', '$utm_term'];3568 var props = store.getProps();3569 for (var i = 0; i < latest_utms.length; i++) {3570 if (latest_utms[i] in props) {3571 delete props[latest_utms[i]];3572 }3573 }3574 store.setProps(props, true);3575 var latestObj = {};3576 if (url_domain === "") {3577 url_domain = "url解析失败";3578 }3579 _.each(sd.para.preset_properties, function(value, key) {3580 if (key.indexOf('latest_') === -1) {3581 return false;3582 }3583 key = key.slice(7);3584 if (value) {3585 if (key !== 'utm' && url_domain === "url解析失败") {3586 latestObj['$latest_' + key] = 'url的domain解析失败';3587 } else if (_.isReferralTraffic(document.referrer)) {3588 switch (key) {3589 case 'traffic_source_type':3590 latestObj['$latest_traffic_source_type'] = _.getSourceFromReferrer();3591 break;3592 case 'referrer':3593 latestObj['$latest_referrer'] = _.info.pageProp.referrer;3594 break;3595 case 'search_keyword':3596 latestObj['$latest_search_keyword'] = _.getKeywordFromReferrer();3597 break;3598 case 'landing_page':3599 latestObj['$latest_landing_page'] = location.href;3600 break;3601 }3602 }3603 } else {3604 if (key === 'utm' && sd.store._state.props) {3605 for (var key1 in sd.store._state.props) {3606 if (key1.indexOf('$latest_utm') === 0 || key1.indexOf('_latest_') === 0) {3607 delete sd.store._state.props[key1];3608 }3609 }3610 } else if (sd.store._state.props && (('$latest_' + key) in sd.store._state.props)) {3611 delete sd.store._state.props['$latest_' + key];3612 }3613 }3614 });3615 sd.register(latestObj);3616 if (sd.para.preset_properties.latest_utm) {3617 var allUtms = _.info.campaignParamsStandard('$latest_', '_latest_');3618 var $utms = allUtms.$utms;3619 var otherUtms = allUtms.otherUtms;3620 if (!_.isEmptyObject($utms)) {3621 sd.register($utms);3622 }3623 if (!_.isEmptyObject(otherUtms)) {3624 sd.register(otherUtms);3625 }3626 }3627 }3628 };3629 var heatmap = sd.heatmap = {3630 setNotice: function(web_url) {3631 sd.is_heatmap_render_mode = true;3632 if (!sd.para.heatmap) {3633 sd.errorMsg = '您SDK没有配置开启点击图,可能没有数据!';3634 }3635 if (web_url && web_url[0] && web_url[1]) {3636 if (web_url[1].slice(0, 5) === 'http:' && location.protocol === 'https:') {3637 sd.errorMsg = '您的当前页面是https的地址,神策分析环境也必须是https!';3638 }3639 }3640 if (!sd.para.heatmap_url) {3641 sd.para.heatmap_url = location.protocol + '//static.sensorsdata.cn/sdk/' + sd.lib_version + '/heatmap.min.js';3642 }3643 },3644 getDomIndex: function(el) {3645 if (!el.parentNode) return -1;3646 var i = 0;3647 var nodeName = el.tagName;3648 var list = el.parentNode.children;3649 for (var n = 0; n < list.length; n++) {3650 if (list[n].tagName === nodeName) {3651 if (el === list[n]) {3652 return i;3653 } else {3654 i++;3655 }3656 }3657 }3658 return -1;3659 },3660 selector: function(el) {3661 var i = el.parentNode && 9 == el.parentNode.nodeType ? -1 : this.getDomIndex(el);3662 if (el.getAttribute && el.getAttribute('id') && (!sd.para.heatmap || (sd.para.heatmap && sd.para.heatmap.element_selector !== 'not_use_id'))) {3663 return '#' + el.getAttribute('id');3664 } else {3665 return el.tagName.toLowerCase() + (~i ? ':nth-of-type(' + (i + 1) + ')' : '');3666 }3667 },3668 getDomSelector: function(el, arr) {3669 if (!el || !el.parentNode || !el.parentNode.children) {3670 return false;3671 }3672 arr = arr && arr.join ? arr : [];3673 var name = el.nodeName.toLowerCase();3674 if (!el || name === 'body' || 1 != el.nodeType) {3675 arr.unshift('body');3676 return arr.join(' > ');3677 }3678 arr.unshift(this.selector(el));3679 if (el.getAttribute && el.getAttribute('id') && (sd.para.heatmap && sd.para.heatmap.element_selector !== 'not_use_id')) return arr.join(' > ');3680 return this.getDomSelector(el.parentNode, arr);3681 },3682 na: function() {3683 var a = document.documentElement.scrollLeft || window.pageXOffset;3684 return parseInt(isNaN(a) ? 0 : a, 10);3685 },3686 i: function() {3687 var a = 0;3688 try {3689 a = o.documentElement && o.documentElement.scrollTop || m.pageYOffset,3690 a = isNaN(a) ? 0 : a;3691 } catch (b) {3692 a = 0;3693 }3694 return parseInt(a, 10);3695 },3696 getBrowserWidth: function() {3697 var a = window.innerWidth || document.body.clientWidth;3698 return isNaN(a) ? 0 : parseInt(a, 10);3699 },3700 getBrowserHeight: function() {3701 var a = window.innerHeight || document.body.clientHeight;3702 return isNaN(a) ? 0 : parseInt(a, 10);3703 },3704 getScrollWidth: function() {3705 var a = parseInt(document.body.scrollWidth, 10);3706 return isNaN(a) ? 0 : a;3707 },3708 W: function(a) {3709 var b = parseInt(+a.clientX + +this.na(), 10);3710 var a = parseInt(+a.clientY + +this.i(), 10);3711 return {3712 x: isNaN(b) ? 0 : b,3713 y: isNaN(a) ? 0 : a3714 }3715 },3716 start: function(ev, target, tagName, customProps, callback) {3717 var userCustomProps = _.isObject(customProps) ? customProps : {};3718 var userCallback = _.isFunction(callback) ? callback : _.isFunction(customProps) ? customProps : undefined;3719 if (sd.para.heatmap && sd.para.heatmap.collect_element && !sd.para.heatmap.collect_element(target)) {3720 return false;3721 }3722 var selector = this.getDomSelector(target);3723 var prop = _.getEleInfo({3724 target: target3725 });3726 prop.$element_selector = selector ? selector : '';3727 if (sd.para.heatmap && sd.para.heatmap.custom_property) {3728 var customP = sd.para.heatmap.custom_property(target);3729 if (_.isObject(customP)) {3730 prop = _.extend(prop, customP);3731 }3732 }3733 prop = _.extend(prop, userCustomProps);3734 if (tagName === 'a' && sd.para.heatmap && sd.para.heatmap.isTrackLink === true) {3735 _.trackLink({3736 event: ev,3737 target: target3738 }, '$WebClick', prop);3739 } else {3740 sd.track('$WebClick', prop, userCallback);3741 }3742 },3743 hasElement: function(e) {3744 var path = e._getPath();3745 if (_.isArray(path) && (path.length > 0)) {3746 for (var i = 0; i < path.length; i++) {3747 if (path[i] && path[i].tagName && (path[i].tagName.toLowerCase() === 'a')) {3748 return path[i];3749 }3750 }3751 }3752 return false;3753 },3754 initScrollmap: function() {3755 if (!_.isObject(sd.para.heatmap) || sd.para.heatmap.scroll_notice_map !== 'default') {3756 return false;3757 }3758 var checkPage = function() {3759 if (sd.para.scrollmap && _.isFunction(sd.para.scrollmap.collect_url) && !sd.para.scrollmap.collect_url()) {3760 return false;3761 }3762 return true;3763 };3764 var interDelay = function(param) {3765 var interDelay = {};3766 interDelay.timeout = param.timeout || 1000;3767 interDelay.func = param.func;3768 interDelay.hasInit = false;3769 interDelay.inter = null;3770 interDelay.main = function(para, isClose) {3771 this.func(para, isClose);3772 this.inter = null;3773 };3774 interDelay.go = function(isNoDelay) {3775 var me = this;3776 var para = {};3777 if (!this.inter) {3778 para.$viewport_position = document.documentElement && document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop || 0;3779 para.$viewport_position = Math.round(para.$viewport_position) || 0;3780 para.$viewport_height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || 0;3781 para.$viewport_width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 0;3782 if (isNoDelay) {3783 interDelay.main(para, true);3784 } else {3785 this.inter = setTimeout(function() {3786 interDelay.main(para);3787 }, this.timeout);3788 }3789 }3790 };3791 return interDelay;3792 };3793 var delayTime = interDelay({3794 timeout: 1000,3795 func: function(para, isClose) {3796 var offsetTop = document.documentElement && document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop || 0;3797 var current_time = new Date();3798 var delay_time = current_time - this.current_time;3799 if ((delay_time > sd.para.heatmap.scroll_delay_time && offsetTop - para.$viewport_position !== 0) || isClose) {3800 para.$url = location.href;3801 para.$title = document.title;3802 para.$url_path = location.pathname;3803 para.event_duration = Math.min(sd.para.heatmap.scroll_event_duration, parseInt(delay_time) / 1000);3804 sd.track('$WebStay', para);3805 }3806 this.current_time = current_time;3807 }3808 });3809 delayTime.current_time = new Date();3810 _.addEvent(window, 'scroll', function() {3811 if (!checkPage()) {3812 return false;3813 }3814 delayTime.go();3815 });3816 _.addEvent(window, 'unload', function() {3817 if (!checkPage()) {3818 return false;3819 }3820 delayTime.go('notime');3821 });3822 },3823 initHeatmap: function() {3824 var that = this;3825 if (!_.isObject(sd.para.heatmap) || sd.para.heatmap.clickmap !== 'default') {3826 return false;3827 }3828 if (_.isFunction(sd.para.heatmap.collect_url) && !sd.para.heatmap.collect_url()) {3829 return false;3830 }3831 if (sd.para.heatmap.collect_elements === 'all') {3832 sd.para.heatmap.collect_elements = 'all';3833 } else {3834 sd.para.heatmap.collect_elements = 'interact';3835 }3836 if (sd.para.heatmap.collect_elements === 'all') {3837 _.addEvent(document, 'click', function(e) {3838 var ev = e || window.event;3839 if (!ev) {3840 return false;3841 }3842 var target = ev.target || ev.srcElement;3843 if (typeof target !== 'object') {3844 return false;3845 }3846 if (typeof target.tagName !== 'string') {3847 return false;3848 }3849 var tagName = target.tagName.toLowerCase();3850 if (tagName === 'body' || tagName === 'html') {3851 return false;3852 }3853 if (!target || !target.parentNode || !target.parentNode.children) {3854 return false;3855 }3856 var parent_ele = target.parentNode.tagName.toLowerCase();3857 if (parent_ele === 'a' || parent_ele === 'button') {3858 that.start(ev, target.parentNode, parent_ele);3859 } else {3860 that.start(ev, target, tagName);3861 }3862 });3863 } else {3864 _.addEvent(document, 'click', function(e) {3865 var ev = e || window.event;3866 if (!ev) {3867 return false;3868 }3869 var target = ev.target || ev.srcElement;3870 if (typeof target !== 'object') {3871 return false;3872 }3873 if (typeof target.tagName !== 'string') {3874 return false;3875 }3876 var tagName = target.tagName.toLowerCase();3877 if (tagName.toLowerCase() === 'body' || tagName.toLowerCase() === 'html') {3878 return false;3879 }3880 if (!target || !target.parentNode || !target.parentNode.children) {3881 return false;3882 }3883 var parent_ele = target.parentNode;3884 if (tagName === 'a' || tagName === 'button' || tagName === 'input' || tagName === 'textarea' || _.hasAttribute(target, 'data-sensors-click')) {3885 that.start(ev, target, tagName);3886 } else if (parent_ele.tagName.toLowerCase() === 'button' || parent_ele.tagName.toLowerCase() === 'a') {3887 that.start(ev, parent_ele, target.parentNode.tagName.toLowerCase());3888 } else if (tagName === 'area' && parent_ele.tagName.toLowerCase() === 'map' && _.ry(parent_ele).prev().tagName && _.ry(parent_ele).prev().tagName.toLowerCase() === 'img') {3889 that.start(ev, _.ry(parent_ele).prev(), _.ry(parent_ele).prev().tagName.toLowerCase());3890 } else {3891 var hasA = that.hasElement(e);3892 if (hasA) {3893 that.start(ev, hasA, hasA.tagName.toLowerCase());3894 }3895 }3896 });3897 }3898 },3899 initDefineMode : function(){3900 function getAndPostDebugInfo(){3901 var arr = [];3902 if(!((window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.sensorsdataNativeTracker && _.isObject(window.SensorsData_iOS_JS_Bridge) && window.SensorsData_iOS_JS_Bridge.sensorsdata_app_server_url)3903 ||(_.isObject(window.SensorsData_APP_New_H5_Bridge) && window.SensorsData_APP_New_H5_Bridge.sensorsdata_get_server_url && window.SensorsData_APP_New_H5_Bridge.sensorsdata_track))){3904 arr.push(sd.debug.defineMode('1'));3905 }3906 if(!(_.isObject(sd.para.app_js_bridge))){3907 arr.push(sd.debug.defineMode('2'));3908 }3909 if(!(_.isObject(sd.para.heatmap) && sd.para.heatmap.clickmap == 'default')){3910 arr.push(sd.debug.defineMode('3'));3911 }3912 if(_.isObject(sd.para.app_js_bridge) && sd.para.app_js_bridge.defineModeDebugInfo == '4'){3913 arr.push(sd.debug.defineMode('4'));3914 }3915 var data = {3916 callType: 'app_alert',3917 data: arr3918 }3919 3920 if(SensorsData_App_Visual_Bridge && SensorsData_App_Visual_Bridge.sensorsdata_visualized_alert_info){3921 SensorsData_App_Visual_Bridge.sensorsdata_visualized_alert_info(JSON.stringify(data));3922 }else if(window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.sensorsdataNativeTracker && window.webkit.messageHandlers.sensorsdataNativeTracker.postMessage){3923 window.webkit.messageHandlers.sensorsdataNativeTracker.postMessage(JSON.stringify(data));3924 }3925 3926 }3927 if(_.isObject(window.SensorsData_App_Visual_Bridge) && window.SensorsData_App_Visual_Bridge.sensorsdata_visualized_mode && ((window.SensorsData_App_Visual_Bridge.sensorsdata_visualized_mode === true) || (window.SensorsData_App_Visual_Bridge.sensorsdata_visualized_mode()))){3928 if(_.isObject(sd.para.heatmap) && sd.para.heatmap.clickmap == 'default'){3929 if(_.isObject(sd.para.app_js_bridge) && sd.para.app_js_bridge.H5verify){3930 _.loadScript({3931 success:function(){3932 setTimeout(function(){3933 if(typeof sa_jssdk_app_define_mode !== 'undefined'){3934 sa_jssdk_app_define_mode(sd);3935 }3936 },0);3937 },3938 error:function(){},3939 type:'js',3940 url: './vapph5define.js'3941 });3942 }else{3943 //打通失败弹框debug信息传给App 3944 getAndPostDebugInfo();3945 }3946 }else{3947 //未开启全埋点弹框3948 getAndPostDebugInfo();3949 }3950 3951 3952 }3953 3954 },3955 prepare: function(todo) {3956 var match = location.search.match(/sa-request-id=([^&#]+)/);3957 var type = location.search.match(/sa-request-type=([^&#]+)/);3958 var web_url = location.search.match(/sa-request-url=([^&#]+)/);3959 var me = this;3960 function isReady(data, type, url) {3961 if (sd.para.heatmap_url) {3962 _.loadScript({3963 success: function() {3964 setTimeout(function() {3965 if (typeof sa_jssdk_heatmap_render !== 'undefined') {3966 sa_jssdk_heatmap_render(sd, data, type, url);3967 if (typeof console === 'object' && typeof console.log === 'function') {3968 if (!(sd.heatmap_version && (sd.heatmap_version === sd.lib_version))) {3969 console.log('heatmap.js与sensorsdata.js版本号不一致,可能存在风险!');3970 }3971 }3972 }3973 }, 0);3974 },3975 error: function() {},3976 type: 'js',3977 url: sd.para.heatmap_url3978 });3979 } else {3980 sd.log('没有指定heatmap_url的路径');3981 }3982 }3983 if (match && match[0] && match[1]) {3984 heatmap.setNotice(web_url);3985 if (_.sessionStorage.isSupport()) {3986 if (web_url && web_url[0] && web_url[1]) {3987 sessionStorage.setItem('sensors_heatmap_url', decodeURIComponent(web_url[1]));3988 }3989 sessionStorage.setItem('sensors_heatmap_id', match[1]);3990 if (type && type[0] && type[1]) {3991 if (type[1] === '1' || type[1] === '2' || type[1] === '3') {3992 type = type[1];3993 sessionStorage.setItem('sensors_heatmap_type', type);3994 } else {3995 type = null;3996 }3997 } else {3998 if (sessionStorage.getItem('sensors_heatmap_type') !== null) {3999 type = sessionStorage.getItem('sensors_heatmap_type');4000 } else {4001 type = null;4002 }4003 }4004 }4005 isReady(match[1], type);4006 } else if (_.sessionStorage.isSupport() && typeof sessionStorage.getItem('sensors_heatmap_id') === 'string') {4007 heatmap.setNotice();4008 isReady(sessionStorage.getItem('sensors_heatmap_id'), sessionStorage.getItem('sensors_heatmap_type'), location.href);4009 } else {4010 me.initDefineMode();4011 todo();4012 if (_.isObject(sd.para.heatmap)) {4013 this.initHeatmap();4014 this.initScrollmap();4015 }4016 }4017 }4018 };4019 sd.init = function(para) {4020 if (sd.readyState && sd.readyState.state && sd.readyState.state >= 2) {4021 return false;4022 }4023 sd.setInitVar();4024 sd.readyState.setState(2);4025 sd.initPara(para);4026 function app_js_bridge() {4027 var app_info = null;4028 var todo = null;4029 function setAppInfo(data) {4030 app_info = data;4031 if (_.isJSONString(app_info)) {4032 app_info = JSON.parse(app_info);4033 }4034 if (todo) {4035 todo(app_info);4036 todo = null;4037 app_info = null;4038 }4039 }4040 function getAndroid() {4041 if (typeof window.SensorsData_APP_JS_Bridge === 'object' && window.SensorsData_APP_JS_Bridge.sensorsdata_call_app) {4042 app_info = SensorsData_APP_JS_Bridge.sensorsdata_call_app();4043 if (_.isJSONString(app_info)) {4044 app_info = JSON.parse(app_info);4045 }4046 }4047 }4048 window.sensorsdata_app_js_bridge_call_js = function(data) {4049 setAppInfo(data);4050 };4051 function calliOS() {4052 if (/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream) {4053 var iframe = document.createElement("iframe");4054 iframe.setAttribute("src", "sensorsanalytics://getAppInfo");4055 document.documentElement.appendChild(iframe);4056 iframe.parentNode.removeChild(iframe);4057 iframe = null;4058 }4059 }4060 sd.getAppStatus = function(func) {4061 calliOS();4062 getAndroid();4063 if (!func) {4064 return app_info;4065 app_info = null;4066 } else {4067 if (app_info === null) {4068 todo = func;4069 } else {4070 func(app_info);4071 app_info = null;4072 }4073 }4074 };4075 }4076 heatmap.prepare(function() {4077 app_js_bridge();4078 _.info.initPage();4079 if (sd.para.is_track_single_page) {4080 _.addSinglePageEvent(function(last_url) {4081 var sendData = function(extraData) {4082 extraData = extraData || {};4083 if (last_url !== location.href) {4084 _.info.pageProp.referrer = last_url;4085 sd.quick("autoTrack", _.extend({4086 $url: location.href,4087 $referrer: last_url4088 }, extraData));4089 }4090 };4091 if (typeof sd.para.is_track_single_page === "boolean") {4092 sendData();4093 } else if (typeof sd.para.is_track_single_page === "function") {4094 var returnValue = sd.para.is_track_single_page();4095 if (_.isObject(returnValue)) {4096 sendData(returnValue);4097 } else if (returnValue === true) {4098 sendData();4099 }4100 }4101 });4102 }4103 if (sd.para.batch_send) {4104 sd.batchSend.batchInterval();4105 }4106 sd.store.init();4107 sd.readyState.setState(3);4108 if (sd._q && _.isArray(sd._q) && sd._q.length > 0) {4109 _.each(sd._q, function(content) {4110 sd[content[0]].apply(sd, Array.prototype.slice.call(content[1]));4111 });4112 }4113 });4114 };4115 var methods = ['track', 'quick', 'register', 'registerPage', 'registerOnce', 'trackSignup', 'setProfile', 'setOnceProfile', 'appendProfile', 'incrementProfile', 'deleteProfile', 'unsetProfile', 'identify', 'login', 'logout', 'trackLink', 'clearAllRegister'];4116 _.each(methods, function(method) {4117 var oldFunc = sd[method];4118 sd[method] = function() {4119 if (!sd.readyState.getState()) {4120 try {4121 console.error('请先初始化神策JS SDK');4122 } catch (e) {4123 sd.log(e);4124 }4125 return;4126 }4127 return oldFunc.apply(sd, arguments);4128 };4129 });4130 if (typeof window['sensorsDataAnalytic201505'] === 'string') {4131 sd.setPreConfig(window[sensorsDataAnalytic201505]);4132 window[sensorsDataAnalytic201505] = sd;4133 window['sensorsDataAnalytic201505'] = sd;4134 sd.init();4135 } else if (typeof window['sensorsDataAnalytic201505'] === 'undefined') {4136 window['sensorsDataAnalytic201505'] = sd;4137 return sd;4138 } else {4139 return window['sensorsDataAnalytic201505'];4140 }4141 } catch (err) {4142 if (typeof console === 'object' && console.log) {4143 try {4144 console.log(err)4145 } catch (e) {4146 sd.log(e);4147 };4148 }4149 }...

Full Screen

Full Screen

z-scores.js

Source:z-scores.js Github

copy

Full Screen

1// Needed elements2let list = $('#methods');3let contentBox = $('.Content');4let graph = $('#normal_curve');5let Submit_button = $('#go');6// All input boxes7let z = $(`#zinput-${list.val()}`);8let score = $(`#xscore-${list.val()}`);9let mean = $(`#mean-${list.val()}`);10let SD = $(`#SD-${list.val()}`);11let resetInputBoxes = () => {12 $("input[type=number]").val(0);13}14// Render the equations (KaTex)15$('#eq-1').append(katex.renderToString("z = \\frac{x - \\mu}{\\sigma}"))16$('#eq-2').append(katex.renderToString("x = z\\sigma + \\mu"))17$('#eq-3').append(katex.renderToString("\\mu = x - z\\sigma"))18$('#eq-4').append(katex.renderToString("\\sigma = \\frac{x - \\mu}{z}"))19// END20// PLOT using (plotly.py)21let plotDistributionCurve = (lowerLimit, upperLimit, xscr, SD, mean, arealeft, arearight) => {22 let X = [], Y = [], Y_till_z_score = [], Y_till_end = [], X_till_z_score = [], X_till_end = [];23 for (let i = lowerLimit; i <= upperLimit; i = i + 0.01){24 y = (1/(Math.sqrt(2*Math.PI)*SD))*(Math.pow(Math.E,(-0.5*Math.pow(((i-mean)/SD), 2))))25 X.push(i);26 Y.push(y);27 if (i < xscr) {28 X_till_z_score.push(i);29 Y_till_z_score.push(y);30 } else if (i > xscr){31 X_till_end.push(i);32 Y_till_end.push(y);33 }34 }35 let trace0 = {36 x: X,37 y: Y,38 fill:'none',39 type:'scatter',40 };41 let trace1 = {42 x: X_till_z_score,43 y: Y_till_z_score,44 fill: 'tozeroy',45 type: 'scatter',46 name: `P(z < 0) = ${arealeft}`47 };48 let trace2 = {49 x: X_till_end,50 y: Y_till_end,51 fill: 'tozeroy',52 type: 'scatter',53 name: `P(z > 0) = ${arearight}`54 };55 layout = {56 plot_bgcolor: "rgba(200,200,200,120)",57 paper_bgcolor: "rgba(200,200,200,120)",58 xaxis: {59 range: [lowerLimit, upperLimit]60 },61 shapes: [{62 type: 'line',63 x0: mean,64 y0: 0,65 x1: mean,66 y1: Math.max(...Y),67 line: {68 color: 'rgb(250, 10, 10)',69 width: 270 }71 }],72 }73 let data = [trace0, trace1, trace2];74 Plotly.newPlot('normal_curve', data, layout);75}76// END77/// If user refreshes the page78if (performance.navigation.type == performance.navigation.TYPE_RELOAD) {79 list.val(1);80 resetInputBoxes(); // Call reset function81}82let getArea = x => {83 // return 0.5 * erfc(-x * Math.SQRT1_2);84 return (1 - erf(-x * Math.SQRT1_2)) * 0.585}86let getZValue = (score, mean, SD) => {87 return ((score - mean)/SD).toFixed(2);88}89// Main logic (hide divs and show divs depending on dropdown box list)90list.change(() => {91 // Clear content div when dropdown list changes92 contentBox.empty();93 graph.empty();94 resetInputBoxes();95 if (list.val() == 1) { // If user chooses 1st option or "Get info from Z-Value"96 $('.getZValue').hide(); // hide97 $('.getScore').hide();98 $('.getSD').hide();99 $('.getMean').hide();100 $('.getInfoFromZValue').show(); // show the right method101 } else if (list.val() == 2) { // If user chooses 2nd option or "Get Z-Value"102 $('.getInfoFromZValue').hide();103 $('.getScore').hide();104 $('.getSD').hide();105 $('.getMean').hide();106 $('.getZValue').show(); // show the right method107 } else if (list.val() == 3) {108 $('.getInfoFromZValue').hide();109 $('.getSD').hide();110 $('.getMean').hide();111 $('.getZValue').hide();112 $('.getScore').show();113 } else if (list.val() == 4) {114 $('.getInfoFromZValue').hide();115 $('.getScore').hide();116 $('.getZValue').hide();117 $('.getSD').hide();118 $('.getMean').show();119 } else if (list.val() == 5) {120 $('.getInfoFromZValue').hide();121 $('.getScore').hide();122 $('.getMean').hide();123 $('.getZValue').hide();124 $('.getSD').show();125 }126 z = $(`#zinput-${list.val()}`);127 score = $(`#xscore-${list.val()}`);128 mean = $(`#mean-${list.val()}`);129 SD = $(`#SD-${list.val()}`);130})131// Allow enter key to submit at the last input box132z.keyup((event) => {133 if (event.keyCode == 13) {134 Submit_button.click();135 }136});137SD.keyup((event) => {138 if (event.keyCode == 13) {139 Submit_button.click() 140 }141})142let showInfo = (zvalue, area) => {143 contentBox.append(`<br>`)144 // contentBox.append(`The z value is: ${zvalue}`);145 contentBox.append(katex.renderToString(`z = ${zvalue}`));146 contentBox.append(`<h3>Less than (left)</h3>`);147 contentBox.append(`<p> The area under the curve is: ${area.toFixed(4)} </p>`);148 contentBox.append(`<p> The probability or P(z < ${zvalue}): ${(area * 100).toFixed(2)}% </p>`);149 contentBox.append(`<h3>Greater than (right)</h3>`);150 contentBox.append(`<p> The area under the curve is: ${(1 - area).toFixed(4)} </p>`);151 contentBox.append(`<p> The probability or P(z > ${zvalue}): ${((1 - area) * 100).toFixed(2)}% </p>`); 152}153Submit_button.click(() => {154 // First we clean the contents of the main content div155 contentBox.empty();156 graph.empty();157 if (list.val() == 1) {158 area = getArea(z.val());159 zvalue = z.val();160 showInfo(zvalue, area);161 plotDistributionCurve(-4, 4, zvalue, 1, 0, area.toFixed(4), (1 - area).toFixed(4));162 } else if (list.val() == 2) {163 area = getArea(getZValue(score.val(), mean.val(), SD.val()));164 zvalue = getZValue(score.val(), mean.val(), SD.val());165 scr = (zvalue * SD.val()) + Number(mean.val());166 showInfo(zvalue, area);167 plotDistributionCurve(Number(mean.val()) - 4*SD.val(), Number(mean.val()) + 4*SD.val(), scr, SD.val(), mean.val(), area.toFixed(4), (1 - area).toFixed(4));168 } else if (list.val() == 3) { // Score169 scr = (z.val() * SD.val()) + Number(mean.val());170 area = getArea(getZValue(scr, mean.val(), SD.val()));171 zvalue = getZValue(scr, mean.val(), SD.val());172 // contentBox.append(`x = ${scr}`);173 contentBox.append(katex.renderToString(`x = ${scr}`));174 showInfo(zvalue, area);175 plotDistributionCurve(Number(mean.val()) - 4*SD.val(), Number(mean.val()) + 4*SD.val(), scr, SD.val(), mean.val(), area.toFixed(4), (1 - area).toFixed(4));176 } else if (list.val() == 4) { // Mean177 mn = Number(score.val()) - (z.val() * SD.val());178 area = getArea(getZValue(score.val(), mn, SD.val()));179 zvalue = getZValue(score.val(), mn, SD.val());180 scr = (zvalue * SD.val()) + mn;181 // contentBox.append(`Mean = ${mn}`);182 contentBox.append(katex.renderToString(`\\mu = ${mn}`));183 showInfo(zvalue, area);184 plotDistributionCurve(Number(mean.val()) - 4*SD.val(), Number(mean.val()) + 4*SD.val(), scr, SD.val(), mn, area.toFixed(4), (1 - area).toFixed(4));185 } else if (list.val() == 5) { // SD186 stdv = (score.val() - mean.val())/z.val()187 area = getArea(getZValue(score.val(), mean.val(), stdv));188 zvalue = getZValue(score.val(), mean.val(), stdv);189 scr = (zvalue * stdv) + Number(mean.val());190 // contentBox.append(`Standard Deviation = ${stdv}`);191 contentBox.append(katex.renderToString(`\\sigma = ${stdv}`));192 showInfo(zvalue, area);193 plotDistributionCurve(Number(mean.val()) - 4*SD.val(), Number(mean.val()) + 4*SD.val(), zvalue, stdv, mean.val(), area.toFixed(4), (1 - area).toFixed(4));194 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { openBrowser, goto, closeBrowser, screenshot } = require('taiko');2(async () => {3 try {4 await openBrowser({ headless: false });5 await goto("google.com");6 await screenshot({ path: "./test.png" });7 } catch (e) {8 console.error(e);9 } finally {10 await closeBrowser();11 }12})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { openBrowser, goto, inputField, write, click, closeBrowser } = require('taiko');2(async () => {3 try {4 await openBrowser();5 await write("Taiko");6 await click("Google Search");7 } catch (e) {8 console.error(e);9 } finally {10 await closeBrowser();11 }12})();

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = {2 async task() {3 await openBrowser();4 await goto("google.com");5 await write("taiko");6 await press("Enter");7 await click("Taiko");8 await screenshot({ path: "./screenshot.png" });9 await closeBrowser();10 }11};

Full Screen

Using AI Code Generation

copy

Full Screen

1var taiko = require('taiko');2taiko.sd({name:'test'});3taiko.sd({name:'test2'});4var taiko = require('taiko');5taiko.sd({name:'test3'});6var taiko = require('taiko');7taiko.sd({name:'test4'});

Full Screen

Using AI Code Generation

copy

Full Screen

1var taiko = require('taiko');2taiko.openBrowser();3taiko.goto('google');4taiko.closeBrowser();5var taiko = require('taiko');6taiko.openBrowser();7taiko.goto('google');8taiko.closeBrowser();9var taiko = require('taiko');10taiko.openBrowser();11taiko.goto('google');12taiko.closeBrowser();13var taiko = require('taiko');14taiko.openBrowser();15taiko.goto('google');16taiko.closeBrowser();17var taiko = require('taiko');18taiko.openBrowser();19taiko.goto('google');20taiko.closeBrowser();21var taiko = require('taiko');22taiko.openBrowser();23taiko.goto('google');24taiko.closeBrowser();25var taiko = require('taiko');26taiko.openBrowser();27taiko.goto('google');28taiko.closeBrowser();29var taiko = require('taiko');30taiko.openBrowser();31taiko.goto('google');32taiko.closeBrowser();33var taiko = require('taiko');34taiko.openBrowser();35taiko.goto('google');36taiko.closeBrowser();37var taiko = require('taiko');

Full Screen

Using AI Code Generation

copy

Full Screen

1import { openBrowser, goto, write, closeBrowser, click, text, focus, $, waitFor, into, toRightOf, scrollDown, screenshot, below, link, button, toLeftOf, textBox, image, fileField, dropDown, checkBox, radioButton, toLeftOf, toRightOf, to, near, above, below, rightOf, leftOf, clear, evaluate, accept, dismiss, prompt, press, hover, doubleClick, rightClick, dragAndDrop, reload, emulateDevice, intercept, toRightOf, toLeftOf, to, near, above, below, rightOf, leftOf, clear, evaluate, accept, dismiss, prompt, press, hover, doubleClick, rightClick, dragAndDrop, reload, emulateDevice, intercept } from 'taiko';2(async () => {3 try {4 await openBrowser();5 await click("Sign in");6 await write("admin");7 await write("admin");8 await click("Sign in");9 await click("Sign

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run taiko automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful