包含相互保密的脚本

Included Scripts Keeping Mutual Secrets

本文关键字:脚本 保密 包含相      更新时间:2023-09-26

通过脚本标签包含在同一页面上的两个脚本是否可以相互保密?

例如,如果一个脚本包含

(function (myArg) {
    //do stuff with secret string
}('secretstring'));

页面上包含的另一个脚本是否有任何途径来确定"secretstring"?

您可以运行以下jQuery代码:

$('script').each(function() {
    alert(this.src); // $(this).html() or .text() will show any inline script content
});

它将显示可用于加载任何脚本内容的URL。

加载的内容将包含"secretString"以及所有javascript。

对于一个剧本来说,要想有所收获,需要做大量的工作。但如果你允许通过网络加载脚本,那就不可能是秘密了。

另一种让人(但不是脚本)看到它的方法是,如果浏览器或机器运行了代理,则可以看到加载的所有内容。这可以通过使用内置或可安装的调试器在各种浏览器中完成。

取决于。

从程序逻辑的角度来看,除非显式导出,否则闭包内部的变量是无法从外部访问的。

从安全角度来看,不能访问变量值,但仍然可以通过toString访问函数的定义。如果一个函数没有链接到全局变量(包括dom),并且它来自外部文件,并且没有嵌入到文档中(在这种情况下,可以使用innerHTML),并且与页面不在同一域中(在那种情况下,可能会将文件加载到iframe中,并读取其源)。。。那么据我所知,没有办法访问它的来源。

还可以覆盖许多内置的javascript函数。因此,以下场景仍然存在(除非您的代码在任何不受信任的代码之前运行,并且不再运行):

<script>
function grab(arg) {
  // do something evil.
}
console.log = grab;
</script>
<script>
(function(myArg) {
  console.log(myArg);
}('secret'));
</script>

Secret不是正确的单词。这被称为自调用匿名函数

(function () {
    // all my code+all my variables
    var a="some value";
    // a can be used anywhere inside this
    // b is unreachable here (it's undefined and hasn't even been instantiated in its own scope yet, as the anonymous function below gets invoked after this one has finished executing)
}());
// a is unreachable here (it's undefined)
(function () {
    // all my code+all my variables
    var b="some value";
    // b can be used anywhere inside this
    // a is unreachable here (it's undefined)
}());
// b is unreachable here (it's undefined)

IIFE(又名自调用匿名函数)对于隔离作用域非常有用。

IIFE在JavaScript中遇到时立即执行。

因此,a和b有不同的作用域,不能在彼此的作用域中使用。

JavaScript中的(function(){})()构造是什么?

http://benalman.com/news/2010/11/immediately-invoked-function-expression/