0

Goal
Set a global variable in one script and access it from another.

Description
In the translator class i have a method which loads custom translations depending on the user language (i take german as example).

export default class Translator {

...   

    loadTranslation(locale) {
        const script = document.createElement('script')
        script.src = path/to/de_custom.js
        document.body.appendChild(script)

        console.log('globalThis', globalThis)
        console.log('loadTranslations', globalThis.tinyMCECustomTranslations)

        return globalThis.tinyMCECustomTranslations
    }
}

Content of the de_custom.js:

function provideTranslations() {
    globalThis.tinyMCECustomTranslations = { test: 'test de' }
}

provideTranslations()

console.log('globalThis', globalThis) shows (tinyMCECustomTranslations exists in line 8):


Window http://localhost:3000/cms/fields/editor/23/de
0: Window http://localhost:3000/cms/fields/editor/23/de
___browserSync___: Object { socketConfig: {…}, socketUrl: "http://localhost:3000/browser-sync", options: {…}, … }
"mce-data-1ffd62qa9": 3
provideTranslations: function provideTranslations()
regeneratorRuntime: Object { wrap: wrap(innerFn, outerFn, self, tryLocsList), isGeneratorFunction: isGeneratorFunction(genFun), mark: mark(genFun), … }
tinyMCE: Object { fire: fire(name, args, bubble), baseURL: "http://localhost:3000/assets/backend", documentBaseURL: "http://localhost:3000/cms/fields/editor/23/", … }
tinyMCECustomTranslations: Object { test: "test de" }
tinymce: Object { fire: fire(name, args, bubble), baseURL: "http://localhost:3000/assets/backend", documentBaseURL: "http://localhost:3000/cms/fields/editor/23/", … }
uidEvent: 7
webpackChunkhybridcms: Array []
​
<default properties>
​
...

But console.log('loadTranslations', globalThis.tinyMCECustomTranslations) shows undefined. Same when i try it with window instead of globalThis.

Does anybody has a hint for me? Where is the point i don't get so far?

leonp5
  • 305
  • 7
  • 23
  • It's not there when you're doing the logging, it's only added later. The console shows you the **then-current** contents of the object when you expand it later. – T.J. Crowder Sep 12 '21 at 14:43
  • When logging an object with `console.log` a reference to that object is passed to the console window, and when you inspect its content there you see the state it has at the time of inspecting it not the one when it was logged. To see the actual content you should use the debugger and a breakpoint. – t.niese Sep 12 '21 at 14:44

0 Answers0