扩展代码如下:
Manifest.json:
{
"manifest_version": 3,
"name": "Remote JS Loader(Manifest V3)",
"version": "2.0",
"host_permissions": ["http://localhost:8000/"],
"background": {
"service_worker": "background.js"
},
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "icon_blog.png",
"48": "icon_discover.png",
"128": "icon_forum.png"
}
}
}
background.js:
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
// 接收来自popup.js的消息
if (message.action === 'loadRemoteScript') {
fetch('http://localhost:8000/test4.js')
.then(response => response.text())
.then(script => {
// 在这里使用下载的脚本
console.log(script);
})
.catch(error => console.error('Error fetching script:', error));
}
});
popup.html
<!DOCTYPE html>
<html>
<head>
<title>Remote JS Loader (Manifest V3)</title>
<script src="popup.js"></script>
</head>
<body>
<h1>Remote JS Loader (Manifest V3)</h1>
<button id="loadButton">Load Remote Script</button>
</body>
</html>
popup.js
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('loadButton').addEventListener('click', function() {
// 在点击按钮时执行的代码
chrome.runtime.sendMessage({ action: 'loadRemoteScript' });
});
});
然后在服务器部署test4.js文件
之后按照扩展,点击弹出窗口按钮,检查源代码,得到以下内容就取到文件了。得到的内容也是test4.js里面的内容。