本文将了解消息发送的工作原理,比如希望和后台进行交互。如下:
修改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 />
</>
)}
</>
)
}
修改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}`})
})