使用较新的 manifest_version:3 ,event 类
项目文件夹:
manifest 是配置文件,Bw 是插件图标,background 是一直可以在后台运行的代码。usr_input 是点击插件图标时会显示的页面,action1 是配合 usr_input 的 js 文件。
manifest 文件代码:
{
"manifest_version": 3,
"name": "助手",
"description": "自动",
"version": "1.0",
"host_permissions": ["http://*/*", "https://*/*"],
"permissions": [
"tabs",
"activeTab",
"scripting"
],
"background": {
"service_worker": "background.js"
},
"action": {
"default_icon": "Bw.png",
"default_title": "自动",
"default_popup":"usr_input.html"
}
}
background 文件:
function checkURL(url){
console.log('URL:'+url);
var flag = false;
if(typeof url == "undefined" || null == url)
url = window.location.href;
// var regex = /.*\:\/\/.*\/form.php/;
var regex = /https\:\/\/.*pretreatment.*/;
var match = url.match(regex);
if(typeof match != "undefined" && null != match)
flag = true;
return flag;
}
usr_input 文件:
<html>
<head>
<meta charset="UTF-8">
<style>
#start1_button {margin-left: 5px;margin-right: 5px;}
</style>
</head>
<body>
<button id="start1_button" type="button" >确定</button>
<script type="text/javascript" src="action1.js"></script>
</body>
</html>
action1 文件:
(这里我把要用的函数都写进去了,为了模块化代码好看,可以采用chrome插件的消息通信机制,参见该文)
// CSS 选择器的详细说明 https://www.w3.org/TR/selectors-3/#sibling-combinators
const replyJKM = () => {
// 函数都要写在里面才能执行
// 自实现 sleep() 函数
const sleep = (time) => {
var startTime = new Date().getTime() + parseInt(time, 10);
while(new Date().getTime() < startTime) { let i=100; }
};
const fireClick = (node) => {
const event = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
node.dispatchEvent(event);
};
const inputValue = (dom, st) => {
var evt = new InputEvent('input', {
inputType: 'insertText',
data: st,
dataTransfer: null,
isComposing: false
});
dom.value = st;
dom.dispatchEvent(evt);
};
const queryByTxt = (css_path,txt='') => {
let qall = document.querySelectorAll (css_path);
if (txt==''){
return qall[0];
}
let rtn = 0;
qall.forEach(element => {
if (element.innerHTML.includes(txt)){
rtn = element; //实际的效果是在找最后一个符合条件的。
}
});
return rtn;
};
// let pc_qs = queryByTxt (" span + svg > path ");
let pc_qs = queryByTxt (" input[placeholder='探索稀土掘金'] ");
fireClick(pc_qs);
sleep(0.3);
inputValue(pc_qs,"nihaoa");
};
document.getElementById('start1_button').onclick = function(element) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.scripting.executeScript(
{
target: { tabId: tabs[0].id },
function: replyJKM
}
// (res) => { /* res contains array with value { result: 8 } */ )
);
});
};
这几个文件准备好以后,将文件夹拖入chrome插件管理页面(打开开发者模式)就安装成功了。