DEV Community

panfan
panfan

Posted on • Originally published at manon.icu on

Chrome插件开发 - Messaging

本文将了解消息发送的工作原理,比如希望和后台进行交互。如下:

zPmZyAzG9

修改src/App.jsx

import React, {useState} from 'react'

export default function Messaging() {
  const [message, setMessage] = useState(null)
  const backgroundRequest = () => {
    chrome.runtime.sendMessage({color}, (response) => {
      setMessage(response.msg)
    })
  }

  return (
    <>
      <button onClick={backgroundRequest}>Background request</button>
      {message && (
        <>
          <p className="text-white">{message}</p>
          <br />
        </>
      )}
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

修改background.js

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (!request.color) {
    sendResponse({msg: `You didn't set any color`})
  }

  sendResponse({msg: `You must really like the color ${request.color}`})
})
Enter fullscreen mode Exit fullscreen mode

Source Code

【Source Code】

Top comments (0)