google / google/jsinterop-generator

Global scope is always assumed to be "window"

Open
#18 4 comments 1 reaction 0 assignees View on GitHub
Dominant language
Java
Stars
85
Forks
24
PR merge metrics
No merged PRs in 30d

Description

ModelHelper.createGlobalJavaType always assumes that `window` is the correct name to use:

```
public static Type createGlobalJavaType(String packagePrefix, String globalScopeClassName) {
Type type = new Type(NAMESPACE);
type.setName(globalScopeClassName);
type.setPackageName(packagePrefix);
type.setNativeNamespace(GLOBAL_NAMESPACE);
type.addAnnotation(
builder()
.type(JS_TYPE)
.isNativeAttribute(true)
.namespaceAttribute("")
.nameAttribute("window")
.build());
return type;
}
```

However, this is only correct in a case like DomGlobal, which only makes sense in a normal window context. For classes like Global, this should instead be something like `self`, so that it works both in windows and in workers (as well as other non-browser JS contexts).

My proposal would be to change this to invoke `nameAttribute("self")`, since that seems as though it should be valid in window and worker contexts alike (see [1], [2]), but perhaps there is a better, more flexible solution?

[1] https://developer.mozilla.org/en-US/docs/Web/API/Window/self
[2] https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/self

In the mean time, objects in Global can't be used. Workarounds for others who find this:
* For `Symbol`, make your own jstype to represent it, with a static function instead of a constructor to create it
* For `JSON`, make your own `JSONType` with static methods instead of instance methods
* For NaN/Infinity/undefined and other global methods, use your own static `@JsProperty`-annotated fields.

In all of these cases, JsPackage.GLOBAL should be used as the namespace to avoid needing to reference window.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.