javascript 下一个Js给出ReferenceError:self未定义

yc0p9oo0  于 2023-08-02  发布在  Java
关注(0)|答案(1)|浏览(138)

我正在取得指涉错误:尝试在下一个js中集成zoom sdk时,未定义self。这是我的代码。这个错误可能是由于在Next Js中的服务器端渲染造成的,但我不知道如何修复它。下面是同样的代码。我从zoom的github示例仓库中选择了下面的代码:https://github.com/zoom/meetingsdk-react-sample/blob/master/src/App-New.js

import React, { useEffect, useState } from 'react';
import ZoomMtgEmbedded from '@zoomus/websdk/embedded';

function Meeting() {
  const [client, setClient] = useState(null);

  useEffect(() => {
    if (typeof window !== 'undefined') {
      const zoomClient = ZoomMtgEmbedded.createClient();

      setClient(zoomClient);
    }
  }, []);

  function getSignature(e) {
    e.preventDefault();

    fetch('/api/zoom/signature', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        meetingNumber: '123456789',
        role: 0,
      }),
    })
      .then((res) => res.json())
      .then((response) => {
        startMeeting(response.signature);
      })
      .catch((error) => {
        console.error(error);
      });
  }

  function startMeeting(signature) {
    const sdkKey = 'YOUR_SDK_KEY';
    const meetingNumber = '123456789';
    const passWord = '';
    const role = 0;
    const userName = 'React';
    const userEmail = '';
    const registrantToken = '';
    const zakToken = '';

    let meetingSDKElement = document.getElementById('meetingSDKElement');

    client.init({
      debug: true,
      zoomAppRoot: meetingSDKElement,
      language: 'en-US',
      customize: {
        meetingInfo: [
          'topic',
          'host',
          'mn',
          'pwd',
          'telPwd',
          'invite',
          'participant',
          'dc',
          'enctype',
        ],
        toolbar: {
          buttons: [
            {
              text: 'Custom Button',
              className: 'CustomButton',
              onClick: () => {
                console.log('custom button');
              },
            },
          ],
        },
      },
    });

    client.join({
      signature: signature,
      sdkKey: sdkKey,
      meetingNumber: meetingNumber,
      password: passWord,
      userName: userName,
      userEmail: userEmail,
      tk: registrantToken,
      zak: zakToken,
    });
  }

  function createClient() {
    if (typeof window !== 'undefined') {
      const zoomClient = ZoomMtgEmbedded.createClient();

      setClient(zoomClient);
    }
  }

  function handleJoinMeetingClick(e) {
    e.preventDefault();

    if (client) {
      getSignature(e);
    } else {
      createClient();
    }
  }

  return (
    <div>
      <h1>Zoom Meeting</h1>

      <div id="meetingSDKElement">
        {/* Zoom Meeting SDK Component View Rendered Here */}
      </div>

      <button onClick={handleJoinMeetingClick}>Join Meeting</button>
    </div>
  );
}

export default Meeting;

字符串

enyaitl3

enyaitl31#

我发现了这个问题并解决了。如果你仍然有这个问题,请查看我发布解决方案的zoom developer community。希望这对很多开发者有帮助。
解决方案就在这里。
我知道为什么会发生这个错误。Next.js在服务器端导入sdk,代码在Node.js环境中执行,这意味着没有窗口对象。因此,错误提示self(窗口对象)未找到。
这个错误的解决方案是你需要在客户端导入sdk。在客户端导入sdk,可以使用useEffect,动态导入zoom sdk。
我实现了组件视图,但您也可以实现客户端视图。下面是我的组件视图解决方案代码。希望这能帮助大家解决这个问题。

// app/page.jsx
"use client"
import { useEffect } from "react";

export default function ZoomMeeting() {
  useEffect(() => {
    initZoomApp();
  }, [])

  return (
    <div>
      <div id="meetingSDKElement">ZOOM HERE</div>
    </div>
  )
}

async function initZoomApp() {
  const { client, clientConf } = await initClient();
  startMeeting(client, clientConf);
}

async function initClient() {
  const ZoomMtgEmbedded = await (await import('@zoomus/websdk/embedded')).default;
  const client = ZoomMtgEmbedded.createClient();

  const clientConf = {
    authEndpoint: process.env.NEXT_PUBLIC_AUTH_ENDPOINT,
    sdkKey: process.env.NEXT_PUBLIC_CLIENT_ID,
    signature: "",
    meetingNumber: '00000000000', // actual meeting number: user need to input
    passWord: 'xxxxxx', // actual password for the meeting: user need to input
    role: 0, // 0 implies client, 1 implies host
    userName: 'React', // username: user need to input
    userEmail: '' // user email: user need to input
  }

// fetch signature to your auth endpoint. Check the sample repo.
// https://github.com/zoom/meetingsdk-auth-endpoint-sample
  const { signature } = await getSignature(clientConf.meetingNumber, clientConf.role);
  clientConf.signature = signature;

  const meetingSDKElement = document.getElementById('meetingSDKElement');
  client.init({
    debug: true,
    zoomAppRoot: meetingSDKElement,
    language: 'en-US',
    customize: {
      meetingInfo: ['topic', 'host', 'mn', 'pwd', 'telPwd', 'invite', 'participant', 'dc', 'enctype'],
      toolbar: {
        buttons: [
          {
            text: 'Custom Button',
            className: 'CustomButton',
            onClick: () => {
              console.log('Hi, mom');
            }
          }
        ]
      }
    }
  });

  return { client: client, clientConf: clientConf };
}

// fetch signature to your auth endpoint. Check the sample repo.
// https://github.com/zoom/meetingsdk-auth-endpoint-sample 
async function getSignature(meetingNumber, role) {
  const data = await fetch(process.env.NEXT_PUBLIC_AUTH_ENDPOINT, {
    method: "POST",
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      meetingNumber: meetingNumber,
      role: role
    })
  })
  const { data: signature } = await data.json();
  return signature;
}

function startMeeting(client, clientConf) {
  client.join({
    signature: clientConf.signature,
    sdkKey: clientConf.sdkKey,
    meetingNumber: clientConf.meetingNumber,
    password: clientConf.passWord,
    userName: clientConf.userName,
    userEmail: clientConf.userEmail,
  })
}

字符串

相关问题