1。前言大家好,我是安国!最近在开发者模式下调试Chrome扩展,发现安装扩展后默认会报错,提示v2版本已经废弃,相关API函数明年将无法使用。建议升级到v3版本。本文以v3版本为基础,盘点Chrome插件开发中的一些要点,供大家参考。2、配置v2升级到v3后,manifest.json配置文件需要修改如下。2-1版本号需要将manifest_version的值设置为3。2-2actionaction可以指定Chrome扩展图标设置,弹出页面等。v3中使用关键字action,而不是v2中的browser_action关键字。//v3..."action":{"default_icon":{"16":"images/icon16.png","32":"images/icon32.png"},"default_popup":"popup.html","default_title":"HelloWorld"}...2-3后台在v2中,我们可以使用scripts关键字指定后台运行的脚本列表,然后使用persistent关键字设置运行脚本的生命周期.当persistent设置为true时,脚本将一直在后台运行,从而消耗系统资源。//v2..."background":{"persistent":false,"scripts":["background.js"]}...所以在v3版本中,使用service_worker关键字智能启动脚本。PS:在v3中,脚本的生命周期不能通过关键字persistent来指定。//v3..."background":{"service_worker":"background.js"}...3。v3中的缓存,使用如下方法将键值对存入缓存。//v3...//存储数据到缓存//Key:chrome.storage.sync.set({username:'AirPython',password:'123456'},function(){console.log("保存成功!")})...从缓存中获取数据,有相应的API。//v3...//获取缓存chrome.storage.sync.get({username:"",password:""},function(items){//用户名和密码不为空if(items.username&&items.password){...}})...4。定时任务在v2中实现定时任务和延时任务非常方便。我们只需要在background.js中创建一个定时任务,然后将persistent设置为true,这样就可以让定时任务一直在后台执行。由于v3切换到了service_worker模式,如果要实现定时任务,只能使用alarms来实现。//v3-manifest.json..."permissions":[..."alarms"]...操作步骤如下:在后台manifest中设置alarms权限,使用alarms创建定时任务//v3背景.js。..functionperoidFunc(){...}//定时器chrome.alarms.onAlarm.addListener((alarm)=>{//ExecuteperoidFunc()});//每1分钟执行一次定时任务chrome.alarms.create({periodInMinutes:1.0});...5.网络请求网络请求的4种主流方式包括:AjaxJqueryfetchAxios这里以fetch的第三种方式为例:...functionlogin_do(tab,username,password){consturl=HOST+'do_login'constparams={headers:{"content-type":"application/json;charset=UTF-8"},body:JSON.stringify({"username":username,"password":password.replace(/(^\s*)|(\s*$)/g,"")//去掉前后空格}),method:"POST"}fetch(url,params).then(data=>{returndata.json()}).then(res=>{if(res.err_code==0){show(res.data.tips,"登录成功")}else{warn(res.错误消息)}})。catch(error=>{console.log(error)warn("Resetfailed,pleasecheckthedata!")})}...6.AutomatedChrome插件可以充分实现一些自动化场景,从而提高效率我们的工作本文中模拟文本框输入的API已被丢弃。推荐使用以下方法完成文本框输入。...//输入函数input(inputElement,content){//注意:evt.initEvent已弃用,请改用以下内容//letevt=document.createEvent('HTMLEvents');//evt.initEvent('输入',true,true);//新方法varevt=newEvent("input",{"bubbles":true,"cancelable":false});文档.dispatchEvent(evt);inputElement.value=内容;inputElement.dispatchEvent(evt)}...7.最后再补充一点,v3版本中的背景不能直接使用window对象。这里推荐通过Tab标签或者消息通信来实现。在开发一些简单的工具插件时,原生的HTML+JS+Jquery完全够用;但是面对一些复杂页面的需求,还是推荐使用“vue+preset”的方式进行快速开发。这部分内容需要的朋友可以自行扩展:https://vue-web-extension.netlify.app/intro/setup.html
