- 必备一个
manifest.json 文件 重点两个配置即下面承担主要逻辑的两个文件:content_script、browser_action
"name": "Mock_Token",
"version": "2.1",
"description": "一个获取用户token的插件",
"manifest_version": 2,
"content_scripts": [
{
"matches": ["http://localhost/*"],
"js": ["content.js"],
"run_at": "document_start"
}
],
"browser_action": {
"default_icon": "32.png",
"default_title": "获取token-Chrome插件",
"default_popup": "./popup.html"
},
"permissions": ["storage", "webRequest", "tabs", "http://*/*", "https://*/*"],
"content_security_policy": "script-src 'self' https://cdn.bootcdn.net; object-src 'self'"
popup.html即点击浏览器状态栏弹出的模态框
<!DOCTYPE html>
<html lang="en">
<head></head>
<style></style>
<body>
<input id="phone" type="text" placeholder="请输入手机号" maxlength="11">
<input id="pwd" type="text" placeholder="请输入密码" maxlength="6">
<button id="btn">确定</button>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script src="./popup.js"></script>
</html>
popup.js 即模态框内容的交互逻辑
const phone = document.querySelector("#phone");
const pwd = document.querySelector("#pwd");
const btn = document.querySelector("#btn");
chrome.storage.sync.get({ phone: "", pwd: "" }, function (items) {
phone.value = items.phone;
pwd.value = items.pwd;
});
btn.addEventListener("click", () => {
getToken(phone.value, pwd.value);
chrome.storage.sync.set({ phone: phone.value, pwd: pwd.value }, function () {
console.log("保存成功!");
});
});
function getToken(phone_no, password) {
let params = {
phone_no: phone_no || "10012345632",
password: password || "123456",
};
const url = "https://xxx.com/login?args=" + JSON.stringify(params);
fetch(url).then((res) => res.json())
.then((res) => {
sendMsg(res.token)
});
}
function sendMsg(token) {
chrome.tabs.query({ active: true, currentWindow: true},
(tabs) => {
const message = { token };
chrome.tabs.sendMessage(tabs[0].id, message);
}
);
}
content.js 即由content-script直接注入到宿主页面内
chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
console.log("接收了来自 popup.js的消息", req.token);
replaceToken(req.token);
});
function replaceToken(token) {
const url = window.location.href;
if (!url.includes("token")) {
window.location.href += url.includes("?")
? `&token=${res.token}`
: `?token=${res.token}`;
} else {
window.location.href = url.replace(/(token=)[^&]+/, "$1" + res.token);
}
setTimeout(() => window.location.reload();, 500);
}