chrome extensions mv3与mv2比较&执行eval

背景

老的扩展项目使用的是mv2版本的API,计划升级mv3版本的时候遇到了下面的问题,这些问题对老项目的影响非常大,所以这里特此记录一下。

1、mv3版本与mv2版本之间的一些区别

这里主要说明的就是mv3版本background.js关于DOM的操作和执行任意字符串js的区别。解决DOM交互和任意JS代码的执行就能完成大部分功能了

  1. mv3的background.js禁用了DOM元素交互(document & window等对象不可用)
    在这里插入图片描述
  2. ▶mv3禁止在background.js执行任意字符串的js(new Function & eval不可用)
    在这里插入图片描述
  3. mv3禁止使用XMLHttpRequest请求改为使用fetch请求(本质上也是background.js禁用对象后不支持了)
    在这里插入图片描述在这里插入图片描述

2、解决mv3版本DOM交互 & JS执行问题

因为mv3不仅在background.js禁用了以上功能,也在content禁用了以上功能。所以说现在mv3版本的扩展不再执行未经扩展审核的js以及相关库的不安全脚本。但是,扩展又不能完全的禁用掉js的执行,所以有了下面在content引入eval5来帮助执行一些js代码和完成解析DOM的操作。

为什么要在conten引入而不是直接在background引入?

因为background.js中禁用了document & window等对象,引入之后服务工作进程就会加载失败了。

2.1、关于引入eval5

eval5-marter
打开上面链接访问github,下载并查看关于eval5的使用。并在manifest.json引入eval5的js库
https://github.com/bplok20010/eval5/blob/master/docs/umd/eval5.min.js
在这里插入图片描述

需要说明的一点是,eval5只支持完成ES5语法,不支持ES6语法,比如箭头函数、let、const等。如果想要写ES6语法,需要使用其他库(babel)将ES6转为ES5语法使用,这里不是重点也不做介绍!

2.2、关于在background.js执行script脚本

https://developer.chrome.com/docs/extensions/reference/scripting/
为了避免跨域一般是在background执行一些跨域的请求(如获取一些html文本、请求一些跨域api),但是请求之后通过message反复的进行消息通信进行数据处理无疑是非常麻烦的!所以引用了mv3支持的chrome.scripting API执行一些内容脚本,完成后将内容直接返回,大大降低了通信成本和代码复杂度。
附部分关键代码,脚本执行 & eval5执行

/**
 * background向content-script执行方法脚本
 * @param {*} tabId 在指定的tabId执行脚本
 * @param {*} func 需要执行脚本的方法名
 * @param {*} args 脚本方法的参数
 * @param {*} callback 执行成功,返回结果的回调
 */
function executeScriptFunc(tabId, func, args, callback) {
  chrome.scripting.executeScript({
    target: {tabId: tabId},
    func: func,
    args: args
  }, (resultArr) => {
    if (callback && resultArr && resultArr.length > 0) {
      // 只取主帧的返回结果
      callback(resultArr[0].result)
    }
  })
}
function testEval5() {
   let interpreter = new eval5.Interpreter(window);
  // let result = interpreter.evaluate(
  //     `   var a = 4;
  //         var b = 3;
  //         var sum = a+b;
  //         console.log('a+b=', sum)
  //     `
  // , {console: console, window: window, document: document})
  // ###
  let result = interpreter.evaluate(
      `   var a = 4;
          var b = 3;
          var sum = a+b;
          console.log('a+b=', sum);
          sum;
      `)
  console.log('eval5执行结果:', result) 
}
function testParseHtml(htmlData) {
  let dom = new DOMParser()
  let doc = dom.parseFromString(htmlData, 'text/html')
  console.log('doc:', doc?.title)
  return doc?.title
}
// 执行eval5调用
executeScriptFunc('your tabId', testEval5, [], (execResult) => {
  console.log(execResult)
})

// 解析html调用
fetch('https://www.baidu.com').then(rsp => { 
    return rsp.text()
}).then(html => {
    executeScriptFunc('your tabId', testParseHtml, [html], (execResult) => {
        console.log('执行结果返回:', execResult)
        sendResponse('ok')
    })
})

eval5执行结果
在这里插入图片描述

补充

    content_script内容脚本不能共享当前窗口的window对象,只能共享DOM元素。
https://developer.chrome.com/extensions/content_scripts#execution-environment

HTML解析执行结果
在这里插入图片描述

3、background执行fetch调用URL

js fetch使用 & 参数

fetch('https://www.baidu.com').then(rsp => { 
  return rsp.text()
}).then(html => {
  console.log(html)
})

参考

谷歌来了也不好使!谁说Chrome插件v3中不能使用eval?

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论
Transform your existing web applications into Google Chrome browser extensions and create brand new extensions that improve your own browsing experience and that of your users. This book shows you how Google Chrome browser extensions are extremely useful tools for enhancing the functionality of the Google Chrome web browser. For example, you can create extensions to summarize the current page you are reading, or to save all of the images in the page you are browsing. They have access to almost all of the features provided by the Google Chrome browser, and they can encapsulate such features in the form of a bundled application providing targeted functionality to users. Extensions also run in a sandboxed environment, making them secure – which is a huge plus in the modern web! The APIs provided by the Chrome Extensions framework help you empower web applications by coupling them with amazing features provided by the Google Chrome web browser, such as bookmarks, history, tabs, actions, storage, notifications, search, and a lot more – facilitating increased productivity on the Google Chrome web browser. What You Will Learn: Transform your web application ideas into Google Chrome Extensions. Choose the recommended components for creating your kind of extension. Leverage the power of a Google Chrome browser by making use of the extensions API. Showcase your existing web-development skills in a modern way by creating useful extensions. Who This Book is For Existing web developers, experienced in creating simple web pages (using HTML, CSS, and JavaScript), to help them create browser extensions for Google Chrome. After understanding the examples and lessons in this book, you will be able to transform your existing web applications into Google Chrome browser extensions, as well as create brand new extensions.
Vue3 与 Vue2 在项目搭建上有一些细微的差别,下面是使用 Vue CLI 创建一个基于 Vue3 的 Chrome 插件项目的步骤: 1. 确保已经安装了最新版本的 Vue CLI: ``` npm install -g @vue/cli ``` 2. 创建一个新的 Vue 项目,添加 `--preset chrome` 参数,表示使用 Chrome 插件预设: ``` vue create my-chrome-extension --preset chrome ``` 3. 进入项目所在的文件夹: ``` cd my-chrome-extension ``` 4. 在 `src/manifest.json` 文件中配置你的 Chrome 插件信息,例如: ``` { "name": "My Chrome Extension", "version": "0.1", "manifest_version": 3, "description": "This is my Chrome extension", "action": { "default_popup": "popup.html" }, "permissions": [ "storage", "activeTab" ] } ``` 5. 在 `public/popup.html` 文件中编写你的 Chrome 插件弹窗内容,例如: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>My Chrome Extension</title> </head> <body> <h1>Hello, world!</h1> <script src="popup.js"></script> </body> </html> ``` 6. 在 `src/popup.js` 文件中编写你的 Chrome 插件弹窗逻辑,例如: ```js console.log('Popup loaded!') ``` 7. 在 `src/background.js` 文件中编写你的 Chrome 插件后台逻辑,例如: ```js chrome.runtime.onInstalled.addListener(() => { console.log('Extension installed!') }) ``` 8. 在 `manifest.json` 文件中设置 `background` 字段,用于指定后台脚本: ``` { // ... "background": { "service_worker": "background.js" } } ``` 9. 运行 `npm run build` 命令编译项目: ``` npm run build ``` 10. 在 Chrome 浏览器中打开 `chrome://extensions/` 页面,点击右上角的“开发者模式”按钮,然后点击“加载已解压的扩展程序”按钮,选择项目中的 `dist` 文件夹即可。 至此,一个基于 Vue3 的 Chrome 插件项目就搭建完成了。你可以在项目的 `src` 文件夹中编写你的插件逻辑,然后通过 `npm run build` 命令打包发布你的插件。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小白说(๑• . •๑)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值