Skip to content

Commit

Permalink
Update the way we get the global object, to comply with CSP no-unsafe…
Browse files Browse the repository at this point in the history
…-eval (#8864)
  • Loading branch information
MarnixBouhuis committed Oct 14, 2021
1 parent 3e02f65 commit 6bc21b5
Showing 1 changed file with 10 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/google/protobuf/compiler/js/js_generator.cc
Expand Up @@ -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++) {
Expand Down

0 comments on commit 6bc21b5

Please sign in to comment.