tradingview / charting-library-examples

Examples of Charting Library integrations with other libraries, frameworks and data transports
MIT License
1.33k stars 744 forks source link

ReferenceError: window is not defined #311

Closed rodrigopluz closed 1 year ago

rodrigopluz commented 1 year ago

Describe the bug

Hello, my application is written in nextjs with typescript, and I'm trying to use the react-typescript example, available in the repository. However it is returning this error below, when I call the new widget(widgetOptions)

Captura de tela de 2022-09-13 09-01-17

Additional context

My component is written like this:

import React, { createRef } from 'react';
import { Content, Title } from './styles';
import {
  widget,
  LanguageCode,
  ResolutionString,
  IChartingLibraryWidget,
  ChartingLibraryWidgetOptions,
} from '../../../public/charting_library/charting_library';

export interface ChartContainerProps {
  symbol: ChartingLibraryWidgetOptions['symbol'];
  interval: ChartingLibraryWidgetOptions['interval'];

  // BEWARE: no trailing slash is expected in feed URL
  datafeedUrl: string;
  libraryPath: ChartingLibraryWidgetOptions['library_path'];
  chartsStorageUrl: ChartingLibraryWidgetOptions['charts_storage_url'];
  chartsStorageApiVersion: ChartingLibraryWidgetOptions['charts_storage_api_version'];
  clientId: ChartingLibraryWidgetOptions['client_id'];
  userId: ChartingLibraryWidgetOptions['user_id'];
  fullscreen: ChartingLibraryWidgetOptions['fullscreen'];
  autosize: ChartingLibraryWidgetOptions['autosize'];
  studiesOverrides: ChartingLibraryWidgetOptions['studies_overrides'];
  container: ChartingLibraryWidgetOptions['container'];
}

export interface ChartContainerState {}

const getLanguageFromURL = (): LanguageCode | null => {
  const regex = new RegExp('[\\?&]lang=([^&#]*)');
  const results = regex.exec(location.search);

  return results === null
    ? null
    : decodeURIComponent(results[1].replace(/\+/g, ' ')) as LanguageCode;
};

const TradingGraph = () => {
  const defaultProps: Omit<ChartContainerProps, 'container'> = {
    symbol: 'AAPL',
    interval: 'D' as ResolutionString,
    datafeedUrl: 'https://demo_feed.tradingview.com',
    libraryPath: '/charting_library/',
    chartsStorageUrl: 'https://saveload.tradingview.com',
    chartsStorageApiVersion: '1.1',
    clientId: 'tradingview.com',
    userId: 'public_user_id',
    fullscreen: false,
    autosize: true,
    studiesOverrides: {},
  };

  let tvWidgets: IChartingLibraryWidget | null = null;
  let ref: React.RefObject<HTMLDivElement> = createRef();

  const widgetOptions: ChartingLibraryWidgetOptions = {
    ...defaultProps,
    // tslint:disable-next-line:no-any
    datafeed: defaultProps.datafeedUrl as any,
    locale: getLanguageFromURL || 'en',
    container: ref.current as HTMLElement,
    enabled_features: ['study_templates'],
    disabled_features: ['use_localstorage_for_settings'],
  };

  if (typeof window !== 'undefined') {
    const tvWidget = new widget(widgetOptions);
    console.log(tvWidget);

    tvWidgets = tvWidget;
    tvWidget.onChartReady(() => {
      tvWidget.headerReady().then(() => {
        const button = tvWidget.createButton();
        button?.setAttribute(
          'title',
          'Click to show a notification popup',
        );
        button?.classList.add('apply-common-tooltip');
        button?.addEventListener('click', () =>
          tvWidget.showNoticeDialog({
            title: 'Notification',
            body: 'TradingView Charting Library API works correctly',
            callback: () => {
              console.log('Noticed!');
            },
          }),
        );
        // button?.innerHTML = 'Check API';
      });
    });

    if (tvWidgets !== null) {
      tvWidgets.remove();
      tvWidgets = null;
    }
  }

  return (
    <Content className="row">
      <Title>Graphics</Title>
      <div ref={ref} className={'TVChartContainer'} />
    </Content>
  );
};

export default TradingGraph;

And even using the given example syntax, it's the same error it returns. and this bug is the same for nextjs-javascript example

tlrjs commented 1 year ago

Make sure you're adding the Githubissues.

  • Githubissues is a development platform for aggregating issues.