Skip to content

Commit b02d5b4

Browse files
Update the way we get the global object, to comply with CSP no-unsafe-eval (#8864)
1 parent 1bc2969 commit b02d5b4

1 file changed

Lines changed: 10 additions & 1 deletion

File tree

src/google/protobuf/compiler/js/js_generator.cc

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3625,7 +3625,16 @@ void Generator::GenerateFile(const GeneratorOptions& options,
36253625
if (options.import_style == GeneratorOptions::kImportCommonJsStrict) {
36263626
printer->Print("var proto = {};\n\n");
36273627
} else {
3628-
printer->Print("var global = Function('return this')();\n\n");
3628+
// To get the global object we call a function with .call(null), this will set "this" inside the
3629+
// function to the global object.
3630+
// This does not work if we are running in strict mode ("use strict"),
3631+
// so we fallback to the following things (in order from first to last):
3632+
// - window: defined in browsers
3633+
// - global: defined in most server side environments like NodeJS
3634+
// - self: defined inside Web Workers (WorkerGlobalScope)
3635+
// - Function('return this')(): this will work on most platforms, but it may be blocked by things like CSP.
3636+
// Function('') is almost the same as eval('')
3637+
printer->Print("var global = (function() { return this || window || global || self || Function('return this')(); }).call(null);\n\n");
36293638
}
36303639

36313640
for (int i = 0; i < file->dependency_count(); i++) {

0 commit comments

Comments
 (0)