From e58469bdbedf514988efa86af9e8e7b5b1fa272f Mon Sep 17 00:00:00 2001 From: Marnix Bouhuis Date: Tue, 26 Oct 2021 18:48:47 +0200 Subject: [PATCH] JS: Fixed `ReferenceError: window is not defined` when getting the global object (#9156) --- src/google/protobuf/compiler/js/js_generator.cc | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/google/protobuf/compiler/js/js_generator.cc b/src/google/protobuf/compiler/js/js_generator.cc index 5542256f38..d2dac2f606 100644 --- a/src/google/protobuf/compiler/js/js_generator.cc +++ b/src/google/protobuf/compiler/js/js_generator.cc @@ -3634,7 +3634,14 @@ void Generator::GenerateFile(const GeneratorOptions& options, // - 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"); + printer->Print( + "var global = (function() {\n" + " if (this) { return this; }\n" + " if (typeof window !== 'undefined') { return window; }\n" + " if (typeof global !== 'undefined') { return global; }\n" + " if (typeof self !== 'undefined') { return self; }\n" + " return Function('return this')();\n" + "}.call(null));\n\n"); } for (int i = 0; i < file->dependency_count(); i++) {