polkadot-js / extension

Simple browser extension for managing Polkadot and Substrate network accounts in a browser. Allows the signing of extrinsics using these accounts. Also provides a simple interface for compliant extensions for dapps.
Apache License 2.0
972 stars 409 forks source link

Error - Window is not defined #1207

Closed insikdev closed 1 year ago

insikdev commented 1 year ago

find same issues about this error ( #1179 , #1101 ).

I can't build next.js proejct and can't refresh page in dev server, but found a solution using dynamic import.

This error is because window object is not defined in non-browser environments.

https://github.com/polkadot-js/extension/blob/895f6a7b99e925b7045681a9bbbb7f430a52440e/packages/extension-dapp/src/bundle.ts#L16

Using globlaThis instead of a window object did not cause the same error.

const win = globalThis as Window & InjectedWindow;

After the fix, the error no longer occurred in my environment. ( next.js 13.1.6 )

jacogr commented 1 year ago

The error is correct - the code is meant to fully execute in a browser environment, not on a server.

yashirooooo commented 1 year ago

The error is correct - the code is meant to fully execute in a browser environment, not on a server.

I am running in react environment. but also reported such an error

jacogr commented 1 year ago

Any browser has "browser" defined.

  1. Open a new browser windo
  2. Open the console
  3. type console.log(window)

The output would be similar to this -

image

This means that if you get this error, your script is not executing in the browser context. In that case, it won't work - @polkadot/extension-dapp interrogates the window object to determine what is injected.

So if you use next.js or any other environment where the JS does not execute on the browser client, but rather the server and then served to the client, your best approach would be to use something like dynamic imports to force the context.

polkadot-js-bot commented 1 year ago

This issue has been open for 21 days with no activity and is not labelled as an enhancement. It will be closed in 7 days.

polkadot-js-bot commented 1 year ago

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue if you think you have a related problem or query.