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

ReferenceError: window is not defined when initialising Realtime in a Service Worker #1013

Closed
snehalbaghel opened this issue Jun 28, 2022 · 11 comments · Fixed by #1016
Closed

Comments

@snehalbaghel
Copy link

snehalbaghel commented Jun 28, 2022

Version: 1.2.25

I'm trying to initialise a realtime connection in a chrome extension Service Worker using ably-webworker.min I'm importing it like so:

import Ably from 'ably/build/ably-webworker.min'

const client = new Ably.Realtime({ ...config })

On creating a realtime object the following error is thrown:

ably-webworker.min.js:1 Uncaught ReferenceError: window is not defined
    at Object.<anonymous> (ably-webworker.min.js:1:1231)
    at Object.<anonymous> (ably-webworker.min.js:1:3006)
    at n (ably-webworker.min.js:1:322)
    at Object.<anonymous> (ably-webworker.min.js:16:23451)
    at n (ably-webworker.min.js:1:322)
    at Object.<anonymous> (ably-webworker.min.js:16:7361)
    at n (ably-webworker.min.js:1:322)
    at Object.<anonymous> (ably-webworker.min.js:16:122194)
    at n (ably-webworker.min.js:1:322)
    at Object.<anonymous> (ably-webworker.min.js:16:164749)

The docs for web workers says that I need to import ably from 'ably/browser/static/ably-webworker.min' however there was no such directory in the package so I ended up using 'ably/build/ably-webworker.min' which is throwing this error.

┆Issue is synchronized with this Jira Uncategorised by Unito

@snehalbaghel snehalbaghel changed the title ReferenceError: window is not defined when initialising Realtime in a Service Worker ReferenceError: window is not defined when initialising Realtime in a Service Worker Jun 28, 2022
@owenpearson
Copy link
Member

Hi @snehalbaghel, thanks for reporting this.

You're right that the docs are out of date for this, 'ably/build/ably-webworker.min' is the correct path for this import. I've opened a PR to update the README.

I've had a go at reproducing the error you're seeing myself but haven't been able to yet. My attempt to reproduce used this source code (compiled with webpack and ts-loader):

import Ably from 'ably/build/ably-webworker.min';

const client = new Ably.Realtime({ key: 'xxx' });

client.connection.on('connected', () => {
  console.log('connected');
});

And this extension manifest:

{
   "name": "Ably extension",
   "description": "Used to test using ably-js in a chrome extension service worker",
   "version": "1.0",
   "manifest_version": 3,
   "permissions": [
      "activeTab",
      "scripting"
   ],
   "background": {
      "service_worker": "background.js"
   }
}

When I load the extension the library logs out 'connected' to the console and doesn't emit any errors.

Could you provide some more detailed instructions on how to reproduce the error you're seeing?

@snehalbaghel
Copy link
Author

Hey @owenpearson thanks for the quick response.

I've had a go at reproducing the error you're seeing myself but haven't been able to yet. My attempt to reproduce used this source code (compiled with webpack and ts-loader):

I'm using Plasmo which has a parcel bundler, it is possible the issue is because of that. I've created a repo to reproduce the error here: https://github.com/snehalbaghel/ably-sw-example, can you see if you're able to reproduce it with this setup?

@owenpearson
Copy link
Member

Thanks @snehalbaghel, that's really helpful. I was able to reproduce the issue using your repo and have opened a PR which fixes it. I'm planning on cutting a new ably-js release either today or tomorrow so you should be fine just using the new version once it's released. Until then, you're welcome to pull down the service-worker-fix ably-js branch and build the library yourself (just npm install and npm run build) to get access to the patched copy of ably-webworker.min.js. Hope this helps, let us know if you have any further questions.

@snehalbaghel
Copy link
Author

Thanks @owenpearson! I'll wait for the new version to be released. Thanks for resolving it so promptly!

@owenpearson
Copy link
Member

Hey @snehalbaghel, just to let you know, we've released version 1.2.26. I've just tested it with your demo repo and it's working as expected now 👍

@snehalbaghel
Copy link
Author

@owenpearson Thanks! I tried it and it seems to create the client without throwing any errors. I'm getting issue with auth now however:

18:07:48.363 Ably: Auth.requestToken(): token request signing call returned error; err = [e29: Request invoked before assigned to; statusCode=500]

Here's the error object that I'm seeing:

{
    "previous": "connecting",
    "current": "disconnected",
    "retryIn": 13905.869679821324,
    "reason": {
        "message": "Client configured authentication provider request failed",
        "code": 80019,
        "statusCode": 401,
        "cause": {
            "message": "[e29: Request invoked before assigned to; statusCode=500]",
            "code": 40170,
            "statusCode": 500
        }
    }
}

I'm able to reproduce it in the same repo. I also tried calling authorize manually but didn't see any request in the network panel:

 client.auth.authorize(undefined, {
    authUrl,
    authHeaders: {
      authorization: token,
      'content-type': 'application/json'
    }
 })

@paddybyers
Copy link
Member

This error response indicates that the library encountered an error when it attempted to make a request to the authUrl - the error [e29: Request invoked before assigned to; statusCode=500] looks like it's either an error response from the authUrl endpoint, or perhaps a problem in attempting to make that request, although I don't recognise that form of error response.

Perhaps the first thing to do would be to enable verbose logging so we can see exactly what request the library attempted to make against the authUrl, and whether or not it succeeded in getting a response.

@owenpearson
Copy link
Member

I've reproduced the issue locally. The problem here is that ably-js internally uses the XMLHttpRequest API for HTTP requests but this API isn't available in the service worker JS environment (same issue as #766). I'm currently looking into adding the fetch API as a fallback.

@snehalbaghel
Copy link
Author

@paddybyers Here are the logs:

Screenshot 2022-07-01 at 1 44 30 PM

console-1656664790444.log

looks like it's either an error response from the authUrl endpoint, or perhaps a problem in attempting to make that request, although I don't recognise that form of error response.

I did not see any request going through in the network tab so it is possible that the attempt failed. I checked our server logs as well but did not find any requests that responded with 500 or 401. Is the library using xhr to make the request as that may not work with service workers.

@owenpearson
Copy link
Member

owenpearson commented Jul 1, 2022

@snehalbaghel While I'm working on fetch API support, a workaround here would be to use the authCallback client option, this would give you control of how the library makes the request to your auth server so you could force it to use the fetch API.

Obviously the implementation will depend on your auth endpoint but example usage would look like this:

new Ably.Realtime({
  authCallback: (tokenParams, callback) => {
    fetch(url, {
      method: 'POST',
      body: JSON.stringify(tokenParams),
    }).then(res => {
      if (!res.ok) {
        res.text().then(body => {
          callback(new Error(`authCallback request failed. body = ${body}`));
        })
      } else {
        res.json().then(tokenDetails => {
          callback(null, tokenDetails);
        });
      }
    });
  },
});

@snehalbaghel
Copy link
Author

@owenpearson Oh that's nice, I did not know about authCallback I'll try it out. Thanks for helping!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging a pull request may close this issue.

3 participants