谷歌浏览器插件开发之消息传递
前言
本项目基于react+vite开发,content.js我用组件的js代替,popup用组件代替
相关代码
content.js
// 发送数据,并打印接收
const onTranslationClick = () => {
chrome.runtime.sendMessage({ type: 'translation' }, function (response) {
console.log(response.message);
});
}
// 按钮事件
<button className='btn btn-success' onClick={onTranslationClick}>一键翻译</button>
// background.js中的代码
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.type === 'translation') {
console.log('开始翻译啦');
// 回复消息
sendResponse({ message: '翻译666' });
}
});
效果
文章目录
关闭
共有 0 条评论