Is It Possible to Sandbox JavaScript Running In the Browser?

前端 未结 15 686
北海茫月
北海茫月 2020-11-22 13:58

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

15条回答
  •  遇见更好的自我
    2020-11-22 14:34

    Where is this user JavaScript coming from?

    There is not much you can do about a user embedding code into your page and then calling it from their browser (see Greasemonkey, http://www.greasespot.net/). It's just something browsers do.

    However, if you store the script in a database, then retrieve it and eval() it, then you can clean up the script before it is run.

    Examples of code that removes all window. and document. references:

     eval(
      unsafeUserScript
        .replace(/\/\/.+\n|\/\*.*\*\/, '') // Clear all comments
        .replace(/\s(window|document)\s*[\;\)\.]/, '') // removes window. or window; or window)
     )
    

    This tries to prevent the following from being executed (not tested):

    window.location = 'http://mydomain.com';
    var w = window  ;
    

    There are a lot of limitations you would have to apply to the unsafe user script. Unfortunately, there is no 'sandbox container' available for JavaScript.

提交回复
热议问题