// ==UserScript== // @name 移动百度优化 // @namespace http://tampermonkey.net/ // @version 0.6 // @description 非百度系浏览器使用百度APP的ua时,会缺少搜索栏和控制栏。本脚本可以改善此情况。 // @author 那年那兔那些事 // @include *://m.baidu.com/s* // @license MIT // @downloadURL none // ==/UserScript== (function() { 'use strict'; function longPress(target, eventFn) {//长按事件 let timer = -1; target.addEventListener("touchstart", function() { timer = setTimeout(function() { eventFn(); }, 400); }) target.addEventListener("touchend", function() { clearTimeout(timer); }) } function fixSearchBar(noAlert){//固定/解除固定顶栏 let head = document.querySelector("#page-hd"); let page=document.querySelector("#page"); let msg; if (head.style.position === "fixed") { head.style.position = ""; page.style.marginTop=""; storageData("set","isFixed",false); msg="顶栏:已解除固定"; } else { head.style.position = "fixed"; page.style.marginTop=getComputedStyle(head).height; storageData("set","isFixed",true); msg="顶栏:已固定顶部"; } console.log(msg); if(!noAlert){ alert(msg); } } function getData(key) {//获取需要的数据 if (key === "ua") { let ua = navigator.userAgent; let isMobile = /mobile/i.test(ua); let isBaidu = /baidu/i.test(ua); return isMobile && isBaidu; } let ls = location.search; if (key === "pd") { return !/pd=/i.test(ls); } if (key === "wd") { let searchWord = /word=/i.test(ls) ? ls.slice(ls.search("word=") + 5) : ""; searchWord = !searchWord && /wd=/i.test(ls) ? ls.slice(ls.search("wd=") + 3) : searchWord; searchWord = searchWord ? decodeURIComponent(searchWord.split("&")[0].replace("+"," ")) : ""; return searchWord } return false; } function storageData(type,key,value){//本地存储相关功能 let name="mobileBaiduOptimizeSettingsData"; let initData={ "isFixed":false } let data=localStorage.getItem(name); try{ data=data?JSON.parse(data):{}; }catch(e){ data={}; } data={...initData,...data}; if(type==="set"){ data[key]=value; data=JSON.stringify(data); localStorage.setItem(name,data); }else if(type==="get"){ return data[key]; } } function createSearchBar() {//创建顶部搜索栏 let extraSearchgBox = document.getElementsByClassName("searchboxtop newsearch-white-style")[0]; let tabLink = document.getElementsByClassName("se-head-tablink")[0]; if (!extraSearchgBox && tabLink) { extraSearchgBox = document.createElement("div"); extraSearchgBox.setAttribute("m-service", "searchbox"); extraSearchgBox.setAttribute("class", "searchboxtop newsearch-white-style"); extraSearchgBox.setAttribute("style", "padding-top:10px"); extraSearchgBox.setAttribute("id", "extraSearchgBox"); extraSearchgBox.innerHTML = "
"; longPress(extraSearchgBox.querySelector(".se-bearicon"), fixSearchBar); tabLink.parentElement.insertBefore(extraSearchgBox, tabLink); if(storageData("get","isFixed")){ fixSearchBar(true); } } } if (getData("ua") && getData("pd")) {//判断是否启动脚本 var t = setTimeout(function() { createSearchBar(); }, 200); setTimeout(function() { clearInterval(t); }, 2000); } })();