javascript - 我可以保护原生 JavaScript 函数吗

标签 javascript security native

有什么方法可以防止用户覆盖原生函数吗?

例子:

var getRand;
(function(){
  'use strict';
  getRand = function(){
    return Math.random();
  }
})();

getRand(); //gives a nice random number

页面加载后,在控制台中覆盖。

Math.random = function (){ return 0 };

getRand(); //gives 0 :(

有什么方法可以防止原生函数被覆盖吗?也许使用 CSP 或密封对象...这甚至可能吗?

最佳答案

其实可以用Object.freeze(Math) :

The Object.freeze() method freezes an object: that is, prevents new properties from being added to it; prevents existing properties from being removed; and prevents existing properties, or their enumerability, configurability, or writability, from being changed. In essence the object is made effectively immutable. The method returns the object being frozen.

Object.freeze(Math);

// This won't work or it won't replace
// the function with the whole string...
Math.random = "hello world"; 

除非任何其他库可能依赖于扩展或修改 Math(例如,polyfill 可能需要向 Math< 添加函数或其他内容 但正如我之前所说,这只是卡住内置对象时可能出现的问题...)。

您还可以卡住个别属性...

...使用 Object.defineProperty(...) 修改现有属性描述符:

Object.defineProperty(Math, "random", { 
    configurable: false,
    writable: false 
});

关于javascript - 我可以保护原生 JavaScript 函数吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37532808/

相关文章:

JavaScript 卡住浏览器

javascript - 就像我们可以在 Sass 中使用 _partials 一样,javascript 有类似的东西吗?

android - React Native WebView,如何存储用户名和密码

wcf - 为什么我可以在嗅探器中将 SSL 通信视为纯文本?

android - 无法在 flutter 中添加对android项目的依赖项

Android NDK 将长值传递给 native 方法

javascript - 什么会导致 Chrome 保存密码失败?

javascript - 用于搜索用户评论 html styler 脚本的术语

mysql - MySQL 应用程序中的安全 Multi-Tenancy

iPhone:如何将包含公钥位的 SecKeyRef 或 NSData 导出为 PEM 格式?