本文最后更新于:2 years ago

background.js
function request(url, config) {
	return new Promise((resolve) => {
		fetch(url, config).then((res) => {
			resolve(res.json())
		})
	})
}

// chrome.runtime.onMessage.addListener(async (req, sender, sendResponse) => {
// 	console.log(req.info)
// 	const res = await request()
// 	console.log(res)
// 	sendResponse(res)
// 	// sendResponse('background 已收到')
// })

chrome.runtime.onConnect.addListener(function (port) {
	if (port.name == 'test') {
		port.onMessage.addListener(async (msg) => {
			console.log('收到长连接消息:', msg)
			const url = msg.match(/(https:\/\/.*?)"/)[1]
			const config = JSON.parse(msg.match(/\{([\S\s]*)\}/)[0])
			const res = await request(url, config)
			port.postMessage(res)
		})
	}
})
content.js
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
	console.log(request.info)
	// chrome.runtime.sendMessage(
	// 	{
	// 		info: request.info,
	// 	},
	// 	(res) => {
	// 		console.log(res)
	// 	}
	// )
	const test = chrome.runtime.connect({
		name: 'test',
	})
	test.postMessage(`fetch("url", {config})`)
	test.onMessage.addListener((res) => {
		console.log(res)
	})
	// sendResponse('content 已收到')
})

const handleElements = () => {
	const oConcepts = document.getElementById('concepts')
	oConcepts.innerText = '测试'
}
// chrome.runtime.sendMessage(
// 	{
// 		info: '我是 content.js',
// 	},
// 	(res) => {
// 		alert(res)
// 	}
// )
popup.js
const oInput = document.getElementById('my-input')
const oBtn = document.getElementById('my-btn')

oBtn.onclick = (e) => {
	chrome.tabs.query(
		{
			active: true,
			currentWindow: true,
		},
		(tabs) => {
			const msg = {
				info: oInput.value,
			}
			chrome.tabs.sendMessage(tabs[0].id, msg, (res) => {
				console.log('pop => content')
				console.log(res)
			})
		}
	)
}
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>Document</title>
		<style>
			body {
				width: 200px;
				height: 150px;
			}
		</style>
	</head>
	<body>
		<div>
			<input id="my-input" type="text" />
			<button id="my-btn">执行</button>
		</div>
		<script src="./js/popup.js"></script>
	</body>
</html>

mainfest.json

{
  "name": "js-plugin",
  "version":"0.1.0",
  "description": "测试",
  "manifest_version": 3,
  "background": {
    "service_worker": "js/background.js"
  },
  "content_scripts":[
    {
      "matches":["<all_urls>"],
      "js": ["js/content.js"]
    }
  ],
  "permissions": ["tabs","scripting","activeTab"],
  "action": {
    "default_popup": "popup.html"
  }
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!

Antd Modal使用函数调用 Previous
CSS骨架屏 Next