1
0
Code Issues Pull Requests Packages Projects Releases Wiki Activity GitHub Gitee

扩展MV3;Double S 快捷搜索功能完善;README完成

This commit is contained in:
程序员小墨 2023-01-07 00:27:58 +08:00
commit 0620de4fa7
18 changed files with 2005 additions and 0 deletions

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 程序员小墨
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

111
README.md Normal file
View File

@ -0,0 +1,111 @@
<div align="center" style="text-align: center;">
<img src="resources/image/logo.png" width="128" style="width: 128px;">
<p>
<b>
<span style="font-size: 20px;">小墨助手 - 一个Chrome浏览器扩展</span>
<br>
<span style="font-size: 15px;"><i>Xiaomo Assistant</i> - a Chrome extension</span>
</b>
</p>
</div>
> ⚠️目前项目只有基础功能,建议过段时间再来逛逛嗷~
## 简介 Overview
小墨助手是一个Chrome浏览器扩展针对Chrome内核浏览器用户旨在提高资料检索及浏览器日常使用时的便捷性及高效性。
*Xiaomo Assistant* is a Chrome browser extension for Chrome kernel browser users, designed to improve the convenience and efficiency of data retrieval and daily use of the browser.
## 功能 Extension Features
小墨助手主要有以下功能:
*Xiaomo Assistant* mainly has the following functions:
| 功能 features | 简介 introduction |
| -------------------------------------------------------- | ------------------------------------------------------------ |
| Double S 快捷搜索<br />Double S quick search | 在浏览器搜索框输入 `ss` 然后按下空格或回车键,即可进入快捷搜索功能<br />接下来可以按照提示进行输入,然后按回车即可<br />Enter `ss` in the omnibox and then press the space or enter key to access the feature.<br /> You can then type as prompted and press Enter. |
| Google 广告屏蔽<br />Google AD blocking | 暂无简介<br />No introduction yet |
| 阅读全文自动展开<br />Expand the full text automatically | 暂无简介<br />No introduction yet |
| 确认页直接跳转<br />Confirm page redirection | 暂无简介<br />No introduction yet |
## 浏览器支持 Browser support
| 浏览器 | 支持情况 |
| --------------- | ----------- |
| Google Chrome | ✔️(107.0.0+) |
| Microsoft Edge | ✔️(107.0.0+) |
| Mozilla Firefox | ❌ |
>**为何不支持Firefox?**
>
>因为Firefox采用的浏览器内核与Chrome、Edge等浏览器不同所以暂时不支持。
>
>**Why not support firefox?**
>
>Cuz Firefox uses a different browser kernel than Chrome, Edge and other browsers
## 快速上手 Quick Start
> 下面以Chrome浏览器为例说明其他浏览器大同小异。
>
> The following uses Chrome as an example. Other browsers are similar.
第一步 下载扩展压缩包并解压:**【下载地址暂未更新】**
Step 1 Download and extracted the extension package: **[Download link hasn't been updated yet]**
第二步 打开您的Chrome浏览器并访问`chrome://extensions/`
Step 2 Open your Chrome browser and access `chrome://extensions/`
> 请确保你已经安装了谷歌浏览器。如果没有安装,[点击此处下载](https://www.google.com/intl/zh-CN/chrome/)
>
> Please make sure you have Google Chrome installed. If not, [click here](https://www.google.com/intl/en-US/chrome/) to download.
第三步 打开开发者模式
Step 3 Open Developer mode.
第四步 点击“加载已解压的扩展程序”按钮
Step 4 Click "Load unzipped Extension" button.
第五步 选择刚刚解压出的文件夹即可完成安装
Step 5 Select the folder we've just extracted to complete the installation.
## 作者 Authors
[程序员小墨](https://github.com/coder-xiaomo)
## 关于 About
### 本项目的前身 Predecessor of the project
> This is a brief introduction to the project's predecessor, which is currently not translated into English
本项目的前身是:[学生助手](https://github.com/bitdance-team/chrome-extension),该项目由[BitDance Team](https://github.com/bitdance-team)(学生团队)开发,是参加第二届青训营的结营项目,获得[第二届青训营最佳创意奖](https://mp.weixin.qq.com/s/6ky6cAiCLjXFhedaMJtxtg)。(团队成员及详细信息可以点击链接查看)
[](https://github.com/coder-xiaomo)作为团队队长一直在思考如何让这个浏览器扩展真正成为一个能够使用的工具。考虑到原有项目功能比较杂乱所以决定重新整理整个项目删繁就简打磨核心功能。目前重新整理了整个项目的代码框架和结构删除了实际意义不大的部分功能将扩展manifest更新至MV3并调整了部分代码。
## 许可证 License
本项目使用MIT许可证授权。请参阅[LICENSE](./LICENSE)文件获取完整许可证文本。
This project is licensed under the MIT License. See the [LICENSE](./LICENSE) file for the full license text.

68
background.js Normal file
View File

@ -0,0 +1,68 @@
// refer: https://developer.chrome.com/docs/extensions/mv3/service_workers/#manifest
console.clear()
console.log("[小墨助手]", "Service Worker init success.")
/**
* 右键菜单
*/
chrome.contextMenus.create({
id: 'bitdance',
title: '小墨助手'
})
chrome.contextMenus.create({
id: 'bitdance-advanced-search',
title: '高级搜索',
parentId: 'bitdance',
// onclick: function (info) {
// }
})
chrome.contextMenus.onClicked.addListener(function (info) {
console.log('当前菜单信息:' + JSON.stringify(info))
console.log("[小墨助手]", "高级搜索 已点击菜单")
})
// Events must be registered synchronously from the start of the page.
chrome.runtime.onInstalled.addListener(() => {
console.log("[小墨助手]", "chrome.runtime.onInstalled.")
chrome.contextMenus.create({
"id": "sampleContextMenu",
"title": "Sample Context Menu",
"contexts": ["selection"]
});
});
//
chrome.commands.onCommand.addListener((command) => {
console.log("[小墨助手]", `Command: ${command}`);
});
/**
* 书签
*/
// This will run when a bookmark is created.
chrome.bookmarks.onCreated.addListener(() => {
// do something
console.log("[小墨助手]", "chrome.bookmarks.onCreated.")
});
// chrome.runtime.onMessage.addListener((message, sender, reply) => {
// chrome.runtime.onMessage.removeListener(event);
// });
const filter = {
url: [
{
urlMatches: 'https://www.baidu.com/.*?',
},
],
};
chrome.webNavigation.onCompleted.addListener((details) => {
console.info("[小墨助手]", "The user has loaded my favorite website!", details);
}, filter);
importScripts("./scripts/advanced-search/background.js");

232
generate-manifest.js Normal file
View File

@ -0,0 +1,232 @@
const path = require("path")
const fs = require("fs")
/**
* manifest 修改之后记得执行下面这条命令重新 generate
* node generate-manifest.js
*
* 或者使用这条命令监控文件变化
* nodemon generate-manifest.js
*/
// Manifest file format: https://developer.chrome.com/docs/extensions/mv3/manifest/
var manifest = {
/**
* Required
*/
"manifest_version": 3,
"name": "小墨助手",
"version": "1.0.0",
/**
* Recommended
*/
"action": {
// 浏览器右上角插件logo
"default_icon": { // optional
"16": "resources/image/logo.png",
"24": "resources/image/logo.png",
"32": "resources/image/logo.png"
},
// 浏览器右上角logo 鼠标悬浮显示文字
"default_title": "点击打开小墨助手 配置页面", // optional, shown in tooltip
"default_popup": "html/popup.html" // optional
},
// "default_locale": "zh",
// 如果需要配置default_locale那么需要创建_locales/zh/messages.json内容框架如下
// { "keyName": { "message": "msg", "description": "desc" } }
"description": "便捷,易用的浏览器小助手",
"icons": { // 插件配置页面图标
"16": "resources/image/logo.png",
"32": "resources/image/logo.png",
"48": "resources/image/logo.png",
"128": "resources/image/logo.png"
},
/**
* Optional
*/
// "author": "developer@example.com",
// "automation": {},
"background": {
// "service_worker": "scripts/service_worker/background.js"
"service_worker": "background.js"
},
// "chrome_settings_overrides": {},
"chrome_url_overrides": {},
"commands": {
// 最多可以设置 4 个快捷键,必须包含 Ctrl 或 Alt
// refer: https://developer.chrome.com/docs/extensions/reference/commands/
// 查看: chrome://extensions/shortcuts
"_execute_action": {
"suggested_key": {
"default": "Alt+Comma",
// "windows": "Alt+Comma",
// "mac": "Alt+Comma",
// "chromeos": "Alt+Comma",
// "linux": "Alt+Comma"
}
},
"toggle-feature-foo": {
"suggested_key": {
"default": "Ctrl+Shift+U",
"mac": "Command+Shift+U"
},
"description": "Toggle feature foo",
"global": true
}
},
"content_scripts": [
{
"matches": [
"<all_urls>",
"*://*/*"
],
"js": [
// "assets/js/lib/jquery.min.js",
// "assets/js/content.js",
// "assets/js/direct-url/url.js",
"scripts/advanced-search/content.js"
],
"css": [],
"run_at": "document_start"
},
// {
// // 屏蔽Google广告模块
// "matches": [
// "*://*/*"
// ],
// "js": [
// // "assets/js/remove-google-ads/removeAds.js"
// ],
// "run_at": "document_start"
// },
// {
// // 自动展开模块
// "matches": [
// "*://blog.csdn.net/*",
// "*://www.it1352.com/*"
// ],
// "js": [
// // "assets/js/lib/jquery.min.js",
// // "assets/js/expand-full-text/expand.js"
// ],
// "run_at": "document_start"
// },
{
// 自动搜索模块
"matches": [
"*://fanyi.qq.com/*",
"*://baike.baidu.com/*",
"*://fanyi.youdao.com/*",
"*://www.cnki.net/*",
"*://qikan.cqvip.com/*",
"*://lib.cqvip.com/*"
],
"js": [
"scripts/advanced-search/content-helper.js"
],
"run_at": "document_start"
}
],
"content_security_policy": {},
"cross_origin_embedder_policy": {},
"cross_origin_opener_policy": {},
// "declarative_net_request": {},
// "devtools_page": "devtools.html",
"event_rules": [],
// "export": {},
// "externally_connectable": {},
"file_browser_handlers": [],
"file_system_provider_capabilities": {},
// "homepage_url": "https://path/to/homepage", // 主页待配置
"host_permissions": [],
// "import": [],
"incognito": "spanning", // spanning, split, or not_allowed
"input_components": [],
// "key": "publicKey",
"minimum_chrome_version": "107",
// "nacl_modules": [],
// "oauth2": {},
"omnibox": {
"keyword": "ss"
},
"optional_host_permissions": [],
"optional_permissions": [],
"options_page": "html/options.html",
"options_ui": {},
"permissions": [
//
"commands",
// 浏览器书签
"bookmarks",
// 右键菜单
"contextMenus",
"storage",
"webNavigation"
],
// "replacement_web_app": "https://example.com", // 待配置
"requirements": {},
"sandbox": {},
// "short_name": "Short Name",
"storage": {},
"tts_engine": {},
// "update_url": "https://path/to/updateInfo.xml",
"version_name": "1.0 beta", // 插件配置页面显示版本
"web_accessible_resources": []
}
function save(beautify = false) {
if (beautify) {
fs.writeFileSync(path.join(__dirname, "./manifest.json"), JSON.stringify(manifest, null, 4))
} else {
fs.writeFileSync(path.join(__dirname, "./manifest.json"), JSON.stringify(manifest))
}
}
save()

View File

@ -0,0 +1 @@
*{margin:0;padding:0}li{list-style:none}a{text-decoration:none}body{background:#a6c1ee}

View File

@ -0,0 +1,17 @@
// 全局样式
* {
margin: 0;
padding: 0;
}
li {
list-style: none;
}
a {
text-decoration: none;
}
body {
background: #a6c1ee;
}

View File

@ -0,0 +1 @@
#popup{min-height:420px;width:300px;margin:12px 5px;user-select:none}#popup .control-panel .btn{width:81px;height:32px;color:#fff;cursor:pointer;background-color:#5ca3ef;border:none;border-radius:4px}#popup .control-panel .btn:hover{background-color:#6fc6ff}#popup .control-panel .btn:active{transform:translate(0, 1px);box-shadow:0px 1px 0px 0px}#popup .setting{width:100%;margin-top:12px}#popup .setting ul li{margin:7px 0;height:44px;border-radius:25px;background:#ffffffc9;padding:0}#popup .setting ul li .setting-item{padding-left:18px;padding-right:2px}#popup .setting ul li .setting-item span{font-size:14px;line-height:44px}#popup .setting ul li .setting-item .button{position:relative;float:right;top:6px;right:6px;width:66px;height:32px;border-radius:100px}#popup .setting ul li .setting-item .button .checkbox{position:relative;width:100%;height:100%;opacity:0;cursor:pointer;z-index:3}#popup .setting ul li .setting-item .button .knobs,#popup .setting ul li .setting-item .button .layer{position:absolute;top:0;right:0;bottom:0;left:0}#popup .setting ul li .setting-item .button .knobs{z-index:2}#popup .setting ul li .setting-item .button .layer{border-radius:100px;width:100%;background-color:#ebf7fc;z-index:1}#popup .setting ul li .setting-item .button .knobs::before{content:"YES";position:absolute;top:2px;left:34px;width:20px;height:10px;color:#fff;font-size:10px;font-weight:bold;text-align:center;line-height:1;padding:9px 4px;background-color:#03a9f4;border-radius:50%}#popup .setting ul li .setting-item .button .checkbox:checked+.knobs:before{content:"NO";left:3px;background-color:#f44336}#popup .setting ul li .setting-item .button .checkbox:checked~.layer{background-color:#fcebeb}#popup .setting ul li .setting-item .button .knobs,#popup .setting ul li .setting-item .button .knobs:before,#popup .setting ul li .setting-item .button .layer{transition:.3s ease all}

111
html/assets/css/popup.less Normal file
View File

@ -0,0 +1,111 @@
#popup {
min-height: 420px;
width: 300px;
margin: 12px 5px;
user-select: none;
.control-panel {
.btn {
width: 81px;
height: 32px;
color: #fff;
cursor: pointer;
background-color: #5ca3ef;
border: none;
border-radius: 4px;
&:hover {
background-color: #6fc6ff;
}
&:active {
transform: translate(0px, 1px);
box-shadow: 0px 1px 0px 0px;
}
}
}
.setting {
width: 100%;
margin-top: 12px;
ul {
li {
margin: 7px 0;
height: 44px;
border-radius: 25px;
background: #ffffffc9;
padding: 0;
.setting-item {
padding-left: 18px;
padding-right: 2px;
span {
font-size: 14px;
line-height: 44px;
}
.button {
position: relative;
float: right;
top: 6px;
right: 6px;
width: 66px;
height: 32px;
border-radius: 100px;
.checkbox {
position: relative;
width: 100%;
height: 100%;
opacity: 0;
cursor: pointer;
z-index: 3;
}
.knobs,
.layer {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
.knobs {
z-index: 2;
}
.layer {
border-radius: 100px;
width: 100%;
background-color: #ebf7fc;
z-index: 1;
}
.knobs::before {
content: "YES";
position: absolute;
top: 2px;
left: 34px;
width: 20px;
height: 10px;
color: #fff;
font-size: 10px;
font-weight: bold;
text-align: center;
line-height: 1;
padding: 9px 4px;
background-color: #03a9f4;
border-radius: 50%;
}
.checkbox:checked + .knobs:before {
content: "NO";
left: 3px;
background-color: #f44336;
}
.checkbox:checked ~ .layer {
background-color: #fcebeb;
}
.knobs,
.knobs:before,
.layer {
transition: 0.3s ease all;
}
}
}
}
}
}
}

108
html/assets/js/popup.js Normal file
View File

@ -0,0 +1,108 @@
$(function() {
/**
* Direct Url
*/
const btnDirectUrl = document.querySelector("#btnDirectUrl");
// 页面加载时,更新界面开关状态
chrome.storage.sync.get("State_DirectUrl", ({ State_DirectUrl }) => {
btnDirectUrl.checked = !State_DirectUrl;
});
// 点击开关时存储按钮状态并刷新页面
btnDirectUrl.addEventListener("change", () => {
chrome.storage.sync.set({ State_DirectUrl: !btnDirectUrl.checked });
refreshPage('Direct Url');
});
/**
* Expand Fulltext
*/
const btnExpandFulltext = document.querySelector("#btnExpandFulltext");
// 页面加载时,更新界面开关状态
chrome.storage.sync.get("State_ExpandFulltext", ({ State_ExpandFulltext }) => {
btnExpandFulltext.checked = !State_ExpandFulltext;
});
// 点击开关时存储按钮状态并刷新页面
btnExpandFulltext.addEventListener("change", () => {
chrome.storage.sync.set({ State_ExpandFulltext: !btnExpandFulltext.checked });
refreshPage('Expand Fulltext');
});
/**
* Google 广告拦截
*/
const btnGoogleAds = document.querySelector("#btnAdsBlock");
// 页面加载时,更新界面开关状态
chrome.storage.sync.get('State_AdsBlock', function(budget) {
btnGoogleAds.checked = !budget.State_AdsBlock;
});
// 点击开关时存储按钮状态并刷新页面
$("#btnAdsBlock").click(function() {
chrome.storage.sync.set({ 'State_AdsBlock': !btnGoogleAds.checked });
chrome.extension.getBackgroundPage().updateAdsBlockStatus(!btnGoogleAds.checked);
refreshPage('Ads Block');
})
/**
* Double S 快捷搜索
*/
const btnSSSearch = document.querySelector("#btnSSSearch");
// 页面加载时,更新界面开关状态
chrome.storage.sync.get('State_SSSearch', function(budget) {
btnSSSearch.checked = !budget.State_SSSearch;
});
// 点击开关时存储按钮状态并刷新页面
$("#btnSSSearch").click(function() {
chrome.storage.sync.set({ 'State_SSSearch': !btnSSSearch.checked });
// refreshPage('SS Search');
})
// ****************************************************************************************************************
/**
* 判断是否是浏览器设置页面
* 即是否是 chrome:// 或 edge:// 开头的链接
* @param {} url
* @returns
*/
function isBrowserSettingPage({url, action, showSorryInfo = true }) {
var protocol, isSettingPage = true;
if(/^chrome:\/\/.*$/.test(url)) {
protocol = "chrome://"
} else if(/^edge:\/\/.*$/.test(url)) {
protocol = "edge://"
} else {
isSettingPage = false;
}
if(showSorryInfo && isSettingPage) {
alert(`十分抱歉,由于浏览器限制,“${protocol}”开头的网站不支持${action}`);
}
return isSettingPage;
}
/**
* 改变开关自动刷新页面
*/
function refreshPage(messageInfo) {
chrome.tabs.query({
active: true,
currentWindow: true
}, (tabs) => {
console.log(tabs);
let message = {
info: messageInfo,
action: "refreshPage"
}
chrome.tabs.sendMessage(tabs[0].id, message, res => {
console.log(res);
})
})
}
})

5
html/assets/lib/jquery.min.js vendored Normal file

File diff suppressed because one or more lines are too long

14
html/options.html Normal file
View File

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>配置 | 小墨助手</title>
</head>
<body>
<h1 style="text-align: center;">
小墨助手 配置页
</h1>
</body>
</html>

66
html/popup.html Normal file
View File

@ -0,0 +1,66 @@
<!doctype html>
<html lang="zh">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>小墨助手</title>
<link rel="stylesheet" href="assets/css/global.css">
<link rel="stylesheet" href="assets/css/popup.css">
</head>
<body>
<div id="popup">
<div class="control-panel">
<button class="btn" id="transform">翻译</button>
<button class="btn" id="btnScreenshot">截图</button>
</div>
<div class="setting">
<ul>
<li>
<div class="setting-item">
<span>Double S 快捷搜索</span>
<div class="button">
<input type="checkbox" id="btnSSSearch" class="checkbox" />
<div class="knobs"></div>
<div class="layer"></div>
</div>
</div>
</li>
<li>
<div class="setting-item">
<span>确认访问页自动跳转</span>
<div class="button">
<input type="checkbox" id="btnDirectUrl" class="checkbox" />
<div class="knobs"></div>
<div class="layer"></div>
</div>
</div>
</li>
<li>
<div class="setting-item">
<span>Google广告屏蔽</span>
<div class="button">
<input type="checkbox" id="btnAdsBlock" class="checkbox" />
<div class="knobs"></div>
<div class="layer"></div>
</div>
</div>
</li>
<li>
<div class="setting-item">
<span>阅读原文自动展开</span>
<div class="button">
<input type="checkbox" id="btnExpandFulltext" class="checkbox" />
<div class="knobs"></div>
<div class="layer"></div>
</div>
</div>
</li>
</ul>
</div>
</div>
<script src="assets/lib/jquery.min.js"></script>
<script src="assets/js/popup.js"></script>
</body>
</html>

1
manifest.json Normal file
View File

@ -0,0 +1 @@
{"manifest_version":3,"name":"小墨助手","version":"1.0.0","action":{"default_icon":{"16":"resources/image/logo.png","24":"resources/image/logo.png","32":"resources/image/logo.png"},"default_title":"点击打开小墨助手 配置页面","default_popup":"html/popup.html"},"description":"便捷,易用的浏览器小助手","icons":{"16":"resources/image/logo.png","32":"resources/image/logo.png","48":"resources/image/logo.png","128":"resources/image/logo.png"},"background":{"service_worker":"background.js"},"chrome_url_overrides":{},"commands":{"_execute_action":{"suggested_key":{"default":"Alt+Comma"}},"toggle-feature-foo":{"suggested_key":{"default":"Ctrl+Shift+U","mac":"Command+Shift+U"},"description":"Toggle feature foo","global":true}},"content_scripts":[{"matches":["<all_urls>","*://*/*"],"js":["scripts/advanced-search/content.js"],"css":[],"run_at":"document_start"},{"matches":["*://fanyi.qq.com/*","*://baike.baidu.com/*","*://fanyi.youdao.com/*","*://www.cnki.net/*","*://qikan.cqvip.com/*","*://lib.cqvip.com/*"],"js":["scripts/advanced-search/content-helper.js"],"run_at":"document_start"}],"content_security_policy":{},"cross_origin_embedder_policy":{},"cross_origin_opener_policy":{},"event_rules":[],"file_browser_handlers":[],"file_system_provider_capabilities":{},"host_permissions":[],"incognito":"spanning","input_components":[],"minimum_chrome_version":"107","omnibox":{"keyword":"ss"},"optional_host_permissions":[],"optional_permissions":[],"options_page":"html/options.html","options_ui":{},"permissions":["commands","bookmarks","contextMenus","storage","webNavigation"],"requirements":{},"sandbox":{},"storage":{},"tts_engine":{},"version_name":"1.0 beta","web_accessible_resources":[]}

12
nodemon.json Normal file
View File

@ -0,0 +1,12 @@
{
"ignore": [
".git",
"node_modules",
".gitignore"
],
"env": {
"NODE_ENV": "development"
},
"ext": "js",
"__ext": "js,json"
}

BIN
resources/image/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,139 @@
console.log("[小墨助手]", "自动搜索模块加载成功")
window.onload = () => {
/**
* 先处理不需要传入参数只需要点击按钮的情况然后再处理需要传入参数的情况
*/
/**
* **********************************************************************************************
*
* 不需要传入参数情况
*
* **********************************************************************************************
*/
switch (window.location.host) {
case "fanyi.qq.com": // 腾讯翻译君
document.getElementsByClassName("language-translate-button")[0].click()
// $(".language-translate-button")[0].click()
clearUrlParams();
return;
}
/**
* **********************************************************************************************
*
* 需要传入参数的情况
*
* **********************************************************************************************
*/
/**
* 定义函数
*/
// 获取 URL 参数
// refer: https://www.cnblogs.com/chen-lhx/p/5198612.html
function getUrlVar(name) {
var vars = [], hash;
let paramString = window.location.href.slice(window.location.href.indexOf('?') + 1)
if (paramString.includes("#"))
paramString = paramString.substring(0, paramString.indexOf("#"))
var hashes = paramString.split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return decodeURIComponent(vars[name] ?? "");
}
// 从URL参数中剔除指定参数
function clearUrlParams() {
// 参数获取完成后,清除页面参数
// History.replaceState() refer: https://developer.mozilla.org/zh-CN/docs/Web/API/History/replaceState
// history.replaceState({}, "", "/");
let urlParams = (location.search + "&").replace(/__xiaomo_extension__=.*?\&/, ""); // 在最后补上一个 & ,然后替换掉 __xiaomo_extension__=xxx&
urlParams = urlParams.substring(0, urlParams.length - 1); // 去掉最后一个 &
history.replaceState({}, "", location.pathname + urlParams);
}
/**
* 开始代码逻辑
*/
// 获取参数
let transText = getUrlVar('__xiaomo_extension__')
console.log("[小墨助手]", "transText:", transText);
// 如果没有传递参数,那么就不执行
if (!transText || transText.trim() == "" || transText == "undefined")
return
switch (window.location.host) {
default:
break;
case "baike.baidu.com": // 百度百科
document.getElementById("query").value = transText
document.getElementById("search").click()
// 跳转新页面,所以不需要清除页面参数
break;
case "fanyi.youdao.com": // 有道翻译
// 插件获取不到 Vue 对象(window.$DOM元素app的properties),但是在控制台可以
// console.log(JSON.stringify(Object.keys(window)))
// console.log(Object.getOwnPropertyDescriptors(app))
// console.log(Object.getOwnPropertyDescriptors(document.getElementById("app")))
// let youdaoVueApp = window.app // window.app.__vue_app__.value // window.$("#app").__vue_app__
// console.log(youdaoVueApp)
// 获取输入框
let input = document.getElementById("js_fanyi_input")
// let submit = document.querySelector(".transBtn.searchBtn.red-button") // 此时页面上没有显示翻译按钮,所以获取不到
// console.log(input)
// 输入文字
input.innerHTML = transText
// 输入框要触发输入事件,才能显示出按钮
// refer: https://blog.csdn.net/weixin_54051261/article/details/125752218
input.dispatchEvent(
new Event("input", {
view: window,
bubbles: true,
cancelable: true,
})
)
// 光标挪到最后
// refer: https://blog.csdn.net/weixin_44461275/article/details/126282272
function keepLastIndex(obj) {
obj.focus(); // 解决ff不获取焦点无法定位问题
var range = window.getSelection(); // 创建range
range.selectAllChildren(obj); // range 选择obj下所有子内容
range.collapseToEnd(); // 光标移至最后
}
keepLastIndex(input)
// 最后清理URL上的参数
clearUrlParams();
break;
case "www.cnki.net": // 中国知网
document.getElementById("txt_SearchText").value = transText
document.querySelector(".search-btn").click()
break;
case "qikan.cqvip.com": // 维普期刊
document.getElementById("searchKeywords").value = transText
document.getElementById("btnSearch").click()
break;
}
console.log("[小墨助手]", "自动搜索模块完成搜索 [" + transText + "]");
}

View File

@ -0,0 +1 @@
console.log("[小墨助手]", "高级搜索功能模块加载成功");