如何修改userAgent

778 阅读1分钟

先试试最简单的方法,直接赋值法

console.log(window.navigator.userAgent);
window.navigator.userAgent = 'xxxx';
console.log(window.navigator.userAgent);

发现失败了☹️,并没有什么用。看看是不是这个对象不可写。

Object.getOwnPropertyDescriptor(window, 'navigator');

果然,做得真绝啊,直接把set函数设为undefined了,一点报错也不给。 那就没办法了吗?肯定是有办法的嘛,要不然别人怎么改的。既然是个对象,就可以设置这个对象的属性,那么重写set属性就可以了。看大招。

function createProperty(value) {
  var _value = value;
  function _get() {
    return _value;
  }
  // 重写setter函数
  function _set(v) {
    _value = v;
  }
  return {
    get: _get,
    set: _set,
  };
}

/**
 * 给定对象,创建或替换它的可写属性
 * @param {Object} objBase  e.g. window
 * @param {String} objScopeName    e.g. "navigator"
 * @param {String} propName    e.g. "userAgent"
 * @param {Any} initValue (optional)   e.g. window.navigator.userAgent
 */
function makePropertyWritable(objBase, objScopeName, propName, initValue) {
  let newProp, initObj;

  if (objBase && objScopeName in objBase && propName in objBase[objScopeName]) {
    if (typeof initValue === 'undefined') {
      initValue = objBase[objScopeName][propName];
    }
    newProp = createProperty(initValue);
    try {
      Object.defineProperty(objBase[objScopeName], propName, newProp);
    } catch (e) {
      initObj = {};
      initObj[propName] = newProp;
      try {
        objBase[objScopeName] = Object.create(objBase[objScopeName], initObj);
      } catch (e) {
        console.error(e);
      }
    }
  }
}

console.log(window.navigator.userAgent);
makePropertyWritable(window, 'navigator', 'userAgent');
window.navigator.userAgent = 'xxx';
console.log(window.navigator.userAgent);

把这段代码直接复制到浏览器,就可以看到效果了。