一、需求背景
我们在实际业务开发中,会遇到接口失效的情况,这个时候重新输入一次密码又比较繁琐,可以借助脚本快速完成登录操作,效果如下
二、安装油猴扩展插件
打开设置里面的拓展程序商店,地址:chromewebstore.google.com/?utm_source… 搜索"油猴",点击安装。
- 将扩展程序固定到网页栏
- 点击添加新脚本
三、脚本说明
// ==UserScript==
// @name 这里是脚本名字
// @description 这里是脚本描述
// @version 1
// @match http://*/*
// @match https://*/*
// @grant GM_registerMenuCommand
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_xmlhttpRequest
// ==/UserScript==
// @version :脚本版本,配置脚本更新使用这个字段比较的
// @match: 脚本命中的激活url
// @grant:这个属性可用来申请GM_*函数和unsafeWindow权限.相当于放在脚本header里面告诉油猴扩展,你需要用些什么东西,然后它就会给你相应的权限.
(function() {
'use strict';
// Your code here...
})();
四、一键登录脚本示范
// ==UserScript==
// @name 快速切换账号登录
// @namespace http://tampermonkey.net/
// @version 1.0
// @description 实现一个浮动面板,支持账号列表管理与切换。
// @author Qwen
// @match *://*/*uranus-sub-tag*
// @match *://*/*bysking*
// @match *://*.bysking.cc/*
// @match *://localhost:*/*
// @grant GM_addStyle
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_registerMenuCommand
// @grant GM_xmlhttpRequest
// ==/UserScript==
(function () {
'use strict';
// 环境密钥
const scMap = {
dev: 'dev111',
test: 'test111',
uat: 'uat111',
};
const keyList = ['ACCESS_TOKEN_KEY'];
const expandKey = 'login_panel_expandKey';
const expandState = localStorage.getItem(expandKey);
const updateExpandState = function (value) {
localStorage.setItem(expandKey, value);
};
function getAuthCode(envStr, Mid, cb) {
let envMap = {
dev: 'https://api-dev.cc/login_get_token_api',
test: 'https://api-test.cc/login_get_token_api',
uat: 'https://api-uat.cc/login_get_token_api',
};
let env = envStr;
let reqUrl = envMap[env];
GM_xmlhttpRequest({
method: 'POST',
url: reqUrl,
headers: {
'Content-Type': 'application/json;charset=UTF-8',
},
data: JSON.stringify({
bizCode: Mid,
bizType: 'MOCK_TEST',
secret: scMap[env],
}),
onload(response) {
let resData = JSON.parse(response.responseText);
console.log('monky 插件获取token的数据', resData.data);
cb(resData.data.token);
},
});
}
const updateToken = (tokenValue) => {
keyList.forEach((key) => {
console.log(key, '设置localStorage本地', tokenValue);
localStorage.setItem(key, JSON.stringify(tokenValue));
sessionStorage.setItem(key, tokenValue);
});
// 本地环境的ey子应用的刷新
if (
window.location.href.includes('localhost') &&
window.location.href.includes('bysking-sub')
) {
let newHref = window.location.href.replace('login', '');
window.location.href = newHref;
} else {
location.reload();
}
};
// 初始化用户数据
const USER_DATA_KEY = 'userLoginList';
let userList = JSON.parse(localStorage.getItem(USER_DATA_KEY)) || [];
// 创建浮动面板
function createPanel() {
const panel = document.createElement('div');
panel.id = 'account-switcher-panel';
panel.style.position = 'fixed';
panel.style.top = '20px';
panel.style.fontSize = '12px';
panel.style.right = '20px';
panel.style.width = '300px';
panel.style.transform = 'scale(0.8)';
panel.style.height = 'auto';
panel.style.backgroundColor = '#E8E8E8';
panel.style.border = '1px solid #ccc';
panel.style.borderRadius = '8px';
panel.style.boxShadow = '0 4px 8px rgba(0, 0, 0, 0.2)';
panel.style.zIndex = '9999';
panel.style.padding = '2px';
panel.style.display = 'flex';
panel.style.flexDirection = 'column';
panel.innerHTML = `
<div id="panel-header" style="display: flex; justify-content: space-between; align-items: center; cursor: move; border: 1px solid rgba(5,5,5,0.06);padding: 4px 8px; border-radius: 4px;">
<h2 style="font-size: 14px;">B端账号切换小助手</h2>
<h6 style="font-size: 10px;">(点击名字登录)</h6>
<button id="toggle-button" style="background: none; border: none; cursor: pointer;color: #1677ff;">收起</button>
</div>
<div id="panel-body" style="margin-top: 10px;">
<ul id="user-list" style="list-style: none; padding: 0;"></ul>
<a id="add-user-btn" style="margin: 10px;color: #1677ff; cursor: pointer; display: flex;justify-content: center;">添加账号</a>
</div>
`;
// 添加到页面
document.body.appendChild(panel);
// 面板展开/收起功能
const toggleButton = panel.querySelector('#toggle-button');
const panelBody = panel.querySelector('#panel-body');
panelBody.style.display = expandState;
toggleButton.addEventListener('click', () => {
if (panelBody.style.display === 'none') {
panelBody.style.display = 'block';
toggleButton.textContent = '收起';
updateExpandState('block');
} else {
panelBody.style.display = 'none';
toggleButton.textContent = '展开';
updateExpandState('none');
}
});
return panel;
}
// 渲染用户列表
function renderUserList(panel) {
const userListContainer = panel.querySelector('#user-list');
userListContainer.innerHTML = '';
userList.forEach((user, index) => {
const li = document.createElement('li');
li.style.display = 'flex';
li.style.justifyContent = 'space-between';
li.style.alignItems = 'center';
li.style.marginBottom = '5px';
li.innerHTML = `
<div style="font-size: 12px;">
<span style="padding-right: 8px;">${index + 1} </span>
<span>${user.name} - ${user.id}</span>
</div>
<div>
<span style="cursor: pointer; margin-right: 5px; color: #1677ff; font-size: 12px;">dev</span>
<span style="cursor: pointer; margin-right: 5px; color: #1677ff; font-size: 12px;">test</span>
<span style="cursor: pointer; margin-right: 5px; color: #1677ff; font-size: 12px;">uat</span>
<a class="edit-btn" data-index="${index}" style="cursor: pointer; margin-right: 5px; color: #1677ff; font-size: 10px;">编辑</a>
<a class="delete-btn" data-index="${index}" style="cursor: pointer; margin-right: 5px; color: #1677ff; font-size: 10px;">删除</a>
</div>
`;
userListContainer.appendChild(li);
// 点击用户打印信息
li.addEventListener('click', (e) => {
let env = e.target.innerText;
let mid = user.id;
if (!env || !mid) {
return;
}
console.log('选中用户:', env, mid, user);
getAuthCode(env, mid, (tokenValue) => {
updateToken(tokenValue);
});
});
// 编辑按钮事件
li.querySelector('.edit-btn').addEventListener('click', (e) => {
e.stopPropagation();
editUser(index);
});
// 删除按钮事件
li.querySelector('.delete-btn').addEventListener('click', (e) => {
e.stopPropagation();
deleteUser(index);
});
});
}
// 添加用户
function addUser() {
const name = prompt('请输入用户名:');
const id = prompt('请输入用户ID:');
if (name && id) {
userList.push({ name, id });
saveUserData();
renderUserList(document.getElementById('account-switcher-panel'));
}
}
// 编辑用户
function editUser(index) {
const user = userList[index];
const newName = prompt('修改用户名:', user.name);
const newId = prompt('修改用户ID:', user.id);
if (newName && newId) {
userList[index] = { name: newName, id: newId };
saveUserData();
renderUserList(document.getElementById('account-switcher-panel'));
}
}
// 删除用户
function deleteUser(index) {
if (confirm('确定删除该用户吗?')) {
userList.splice(index, 1);
saveUserData();
renderUserList(document.getElementById('account-switcher-panel'));
}
}
// 保存用户数据到 localStorage
function saveUserData() {
localStorage.setItem(USER_DATA_KEY, JSON.stringify(userList));
}
// 拖拽功能
function makeDraggable(panel) {
const header = panel.querySelector('#panel-header');
let isDragging = false;
let offsetX = 0;
let offsetY = 0;
header.addEventListener('mousedown', (e) => {
isDragging = true;
offsetX = e.clientX - panel.offsetLeft;
offsetY = e.clientY - panel.offsetTop;
});
document.addEventListener('mousemove', (e) => {
if (isDragging) {
let x = e.clientX - offsetX;
let y = e.clientY - offsetY;
// 限制在可视区域内
const maxX = window.innerWidth - panel.offsetWidth;
const maxY = window.innerHeight - panel.offsetHeight;
x = Math.max(0, Math.min(x, maxX));
y = Math.max(0, Math.min(y, maxY));
panel.style.left = `${x}px`;
panel.style.top = `${y}px`;
}
});
document.addEventListener('mouseup', () => {
isDragging = false;
});
}
// 初始化
function init() {
const panel = createPanel();
renderUserList(panel);
makeDraggable(panel);
// 绑定添加用户按钮事件
panel.querySelector('#add-user-btn').addEventListener('click', addUser);
}
// 启动脚本
init();
})();
五 结语
兄弟姐妹们,都看到这里了,点一波关注再走呗~