DEV Community

panfan
panfan

Posted on

Chrome插件开发 - External requests

到目前为止,我们的浏览器插件已经具备了内容展示和交互。

接下来为浏览器添加一些其他的请求数据。

Weather API

打开OpenWeather,注册、登录,然后申请 api,如图:

BkjOBD

添加.env文件,将申请的 api 写入

VITE_APP_API_URL='https://api.openweathermap.org/data/2.5'
VITE_APP_API_KEY='YOUR_KEY'
Enter fullscreen mode Exit fullscreen mode

创建Weather.jsx

export default function Weather() {
  return (
    <div>
      <h2>The weather today ☁️</h2>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

App.jsx组件内引入Weather.jsx

import Counter from './Counter'
import Weather from './Weather'

export function App() {
  return (
    <div className="flex flex-col items-center justify-center w-screen h-screen bg-indigo-400 text-6xl font-bold text-white">
      <p>Welcome 👋</p>
      <br />
      <Weather />
      <br />
      <Counter />
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Weather.jsx引入 hooks 状态

import {useEffect, useState} from 'react'

export default function Weather() {
  const [latLng, setLatLng] = useState({})
  const [data, setData] = useState(null)

  useEffect(() => {
    if (!latLng.lat && !latLng.long) {
      navigator.geolocation.getCurrentPosition(function (position) {
        setLatLng({
          lat: position.coords.latitude,
          long: position.coords.longitude
        })
      })
    }
  }, [latLng])
}
Enter fullscreen mode Exit fullscreen mode

当获取经纬度权限被允许,将会返回当前经纬度,就可以请求天气接口了

import {useEffect, useState} from 'react'

export default function Weather() {
  const [latLng, setLatLng] = useState({})
  const [data, setData] = useState(null)
  useEffect(() => {
    if (!latLng.lat && !latLng.long) {
      navigator.geolocation.getCurrentPosition(function (position) {
        setLatLng({
          lat: position.coords.latitude,
          long: position.coords.longitude
        })
      })
      return
    }
    if (!data) {
      fetch(
        `${import.meta.env.VITE_APP_API_URL}/weather/?lat=${latLng.lat}&lon=${
          latLng.long
        }&units=metric&APPID=${import.meta.env.VITE_APP_API_KEY}`
      )
        .then((res) => res.json())
        .then((result) => setData(result))
    }
  }, [latLng])
}
Enter fullscreen mode Exit fullscreen mode

CxW8Dv

Source Code

【Source Code】

Top comments (0)