一、簡介
暴力猴是一款腳本管理器,可以在瀏覽器中載入並運行用戶自定義的JavaScript腳本,可用於增強瀏覽器功能,改變網站外觀等。暴力猴可運行於Chrome、Firefox、Opera等主流瀏覽器。
二、安裝和使用
安裝暴力猴很簡單,只需在瀏覽器應用商店中搜索並下載即可。安裝完成後,在瀏覽器右上角會出現暴力猴圖標,單擊即可進入腳本管理界面。在此界面中,用戶可進行新建、編輯、刪除、禁用腳本等操作,同時也可對全局配置進行修改。
編寫暴力猴腳本可使用任意文本編輯器,將代碼複製到暴力猴中即可運行。用戶可在編寫腳本時參考暴力猴提供的API進行操作。下面是一段實現將豆瓣圖書評分轉化為星級顯示的例子:
// ==UserScript== // @name 轉換豆瓣圖書評分為星級 // @namespace none // @version 1 // @description 將豆瓣圖書評分轉化為星級顯示 // @author Leo // @match https://book.douban.com/* // @grant none // ==/UserScript== (function() { 'use strict'; // 獲取豆瓣評分元素 let score = document.querySelector('.rating_num'); if(score) { // 將評分轉成星級 let score_star = Math.round(parseFloat(score.textContent) / 2); score.innerHTML = ''; for(let i = 0; i < 5; i++) { let icon = '<i class="fas fa-star"' + (i < score_star ? 'style="color: #e3cf7a;"' : '') + '></i>'; score.innerHTML += icon; } } })();
三、常用功能
1. 頁面自動跳轉
暴力猴腳本可在頁面載入完成後自動跳轉到指定網頁,如下所示:
// ==UserScript== // @name 自動跳轉到百度 // @namespace none // @version 1 // @description 頁面自動跳轉到百度 // @author Leo // @match https://www.baidu.com/* // @grant none // ==/UserScript== (function() { 'use strict'; // 延時2秒跳轉,可根據需要自行修改 setTimeout(() => { window.location.href = 'https://www.baidu.com/'; }, 2000); })();
2. 頁面元素修改
暴力猴腳本可對頁面元素進行添加、刪除、替換等操作,如下所示:
// ==UserScript== // @name 修改搜索框背景色 // @namespace none // @version 1 // @description 將百度搜索框背景色改為紅色 // @author Leo // @match https://www.baidu.com/* // @grant none // ==/UserScript== (function() { 'use strict'; // 修改搜索框樣式 let search_box = document.querySelector('#kw'); if(search_box) { search_box.style.backgroundColor = 'red'; } })();
3. Ajax請求攔截
暴力猴腳本可攔截頁面中的Ajax請求並進行處理,如下所示:
// ==UserScript== // @name 攔截Ajax請求 // @namespace none // @version 1 // @description 攔截頁面中的Ajax請求並修改返回值 // @author Leo // @match https://www.example.com/* // @grant none // ==/UserScript== (function() { 'use strict'; // 攔截Ajax請求 let original_fetch = window.fetch; window.fetch = function (url, init, ...args) { if (url.indexOf('/api') > -1) { // 修改請求返回值 let fake_resp = { data: { user: 'test' } }; let new_resp = new Response(JSON.stringify(fake_resp)); return Promise.resolve(new_resp); } return original_fetch.apply(this, [url, init, ...args]); } })();
四、總結
暴力猴是一款非常強大的腳本管理器,在網頁開發、瀏覽器定製等方面都有著廣泛的應用。學會使用暴力猴腳本能夠極大地提高工作效率,讓我們的網頁瀏覽體驗更加個性化。
原創文章,作者:VOKUY,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/333590.html