cross.js 1.54 KB
/**
 * 跨域发送信息工具库
 */
var config = require('./config');

var yasPath = config.yasPath;

var yasImgDomain = config.yasImgDomain;

var yasMobileDomain = config.yasMobileDomain;

var createCORSRequest = function(method, url) {
  var xhr;
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  } else if (typeof XDomainRequest != "undefined") {
    // IE8 & IE9
    xhr = new XDomainRequest();
  } else if (window.ActiveXObject) {
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
  }
  return xhr;
};


//发送图片方式
exports.imgSend = function(param, callback) {
  if (window.fromApp || window.qs.app_version || window.qs.appVersion) {
    // 从app中打开的wap页场合,走app的上报逻辑
    return;
  }
  var image = new Image(1, 1);
  image.src = yasImgDomain + yasPath + '?' + param;
  image.onload = function() {
    image.onload = null;
    if (callback) {
      callback();
    }
  };
};

// app中打开wap页 数据上报
exports.appSend = function(data, callback) {
  if (!window.fromApp) {
    return;
  }

  var xhr = createCORSRequest();
  if (!xhr) return;
  
  xhr.ontimeout = function(e) {
    console.log("timeout: ", JSON.stringify(e));
  };
  xhr.onerror = function(e) {
    console.log("error: ", JSON.stringify(e));
  };
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status == 200 && callback) {
        callback();
      }
    }
  };
  xhr.open('post', yasMobileDomain, true);
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xhr.send(data);
}