How to avoid accidentally implicitly referring to properties on the global object?

前端 未结 5 1804
面向向阳花
面向向阳花 2020-11-30 09:27

Is it possible to execute a block of code without the implicit with(global) context that all scripts seem to have by default? For example, in a browser, would t

5条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 09:46

    Perhaps slightly cleaner (YMMV) is to set getter traps (like you did), but in a worker so that you don't pollute your main global scope. I didn't need to use with though, so perhaps that is an improvement.

    Worker "Thread"

    //worker; foo.js
    addEventListener('message', function ({ data }) {
      try {
        eval(`
          for (k in self) {
            Object.defineProperty(self, k, {
              get: function () {
                throw new ReferenceError(':(');
              }
            });
          }
          // code to execute
          ${data}
        `);
        postMessage('no error thrown ');
      } catch (e) {
        postMessage(`error thrown: ${e.message}`);
      }
    });
    

    Main "Thread"

    var w = new Worker('./foo.js');
    w.addEventListener('message', ({data}) => console.log(`response: ${data}`));
    w.postMessage('const foo = location');
    


    Another option that may be worth exploring is Puppeteer.

提交回复
热议问题