Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Accessing WorkerGlobalScope instance in web Worker using package:web and js interop #251

Open
andynewman10 opened this issue Jun 3, 2024 · 1 comment
Labels
type-question A question about expected behavior or functionality

Comments

@andynewman10
Copy link

When writing a Web worker using Dart, using the now deprecated dart:html package, it is possible to access the WorkerGlobalScope instance this way:

import 'dart:html'; // deprecated

void test() {
  WorkerGlobalScope.instance.importScripts("...");
}

Using package:web, how can I do the same?

import 'package:web/web.dart' as web;
import 'dart:js_interop';

void test() {
  web.WorkerGlobalScope.instance // not working. 
  // The only way I found is unsafe
  // import 'dart:js_interop_unsafe'; is needed
  globalContext.callMethod('importScripts'.toJS, "https://my/url.js".toJS);
}

I see WorkerGlobalScope is defined in package:web's lib/src/dom/html.dart file, suggesting Worker APIs are supported. But WorkerGlobalScope is an extension, not a class. How can I use it?

@srujzs srujzs added the type-question A question about expected behavior or functionality label Jun 3, 2024
@srujzs
Copy link
Contributor

srujzs commented Jun 3, 2024

The globalContext is the WorkerGlobalScope (which is an extension type) you want here (in dart:html, we just return self for instance), so just cast and use the result:

var globalScope = globalContext as WorkerGlobalScope;
globalScope.importScripts("https://my/url.js");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type-question A question about expected behavior or functionality
Projects
None yet
Development

No branches or pull requests

2 participants