从远程服务器请求JS文件-Manifest V3

本文介绍了如何使用Chrome扩展API(如ManifestV3、ServiceWorker和RuntimeAPI)实现远程JavaScript文件(如test4.js)的加载和在popup中与服务器交互。用户通过点击按钮触发加载过程,实现跨源资源的加载并查看其内容。
摘要由CSDN通过智能技术生成

扩展代码如下:

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里面的内容。

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值