Update the way we get the global object, to comply with CSP no-unsafe-eval (#8864)

This commit is contained in:
Marnix Bouhuis 2021-10-15 00:15:20 +02:00 committed by GitHub
parent 3e02f65f5c
commit 6bc21b531e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -3625,7 +3625,16 @@ void Generator::GenerateFile(const GeneratorOptions& options,
if (options.import_style == GeneratorOptions::kImportCommonJsStrict) {
printer->Print("var proto = {};\n\n");
} else {
printer->Print("var global = Function('return this')();\n\n");
// To get the global object we call a function with .call(null), this will set "this" inside the
// function to the global object.
// This does not work if we are running in strict mode ("use strict"),
// so we fallback to the following things (in order from first to last):
// - window: defined in browsers
// - global: defined in most server side environments like NodeJS
// - self: defined inside Web Workers (WorkerGlobalScope)
// - Function('return this')(): this will work on most platforms, but it may be blocked by things like CSP.
// Function('') is almost the same as eval('')
printer->Print("var global = (function() { return this || window || global || self || Function('return this')(); }).call(null);\n\n");
}
for (int i = 0; i < file->dependency_count(); i++) {