是否可以对在浏览器中运行的 JavaScript 进行沙箱处理? [英] Is it possible to sandbox JavaScript running in the browser?

查看:23
本文介绍了是否可以对在浏览器中运行的 JavaScript 进行沙箱处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以对在浏览器中运行的 JavaScript 进行沙箱处理,以防止访问 HTML 页面中运行的 JavaScript 代码通常可用的功能.

I'm wondering if it's possible to sandbox JavaScript running in the browser to prevent access to features that are normally available to JavaScript code running in an HTML page.

例如,假设我想为最终用户提供一个 JavaScript API,让他们定义在有趣的事件"发生时要运行的事件处理程序.发生,但我不希望这些用户访问 window 对象的属性和功能.我能做到吗?

For example, let's say I want to provide a JavaScript API for end users to let them define event handlers to be run when "interesting events" happen, but I don't want those users to access the properties and functions of the window object. Am I able to do this?

在最简单的情况下,假设我想阻止用户调用 alert.我能想到的几种方法是:

In the simplest case, let's say I want to prevent users calling alert. A couple of approaches I can think of are:

  • 全局重新定义 window.alert.我认为这不是一种有效的方法,因为在页面中运行的其他代码(即,不是由用户在其事件处理程序中编写的内容)可能想要使用 alert.
  • 将事件处理程序代码发送到服务器进行处理.我不确定将代码发送到服务器进行处理是否正确,因为事件处理程序需要在页面上下文中运行.
  • Redefine window.alert globally. I don't think this would be a valid approach because other code running in the page (i.e., stuff not authored by users in their event handlers) might want to use alert.
  • Send the event handler code to the server to process. I'm not sure that sending the code to the server to process is the right approach, because the event handlers need to run in the context of the page.

也许服务器处理用户定义的函数然后生成要在客户端上执行的回调的解决方案可行吗?即使这种方法有效,有没有更好的方法来解决这个问题?

Perhaps a solution where the server processes the user defined function and then generates a callback to be executed on the client would work? Even if that approach works, are there better ways to solve this problem?

推荐答案

Google Caja is a source-to-source 翻译器,允许您将不受信任的第三方 HTML 和 JavaScript 内嵌在您的页面中,并且仍然安全."

Google Caja is a source-to-source translator that "allows you to put untrusted third-party HTML and JavaScript inline in your page and still be secure."

这篇关于是否可以对在浏览器中运行的 JavaScript 进行沙箱处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆