【Chrome Extension】二、导航栏快速查询

【Chrome Extension】二、导航栏快速查询

介绍

导航栏,输入fei,然后tab可进入当前扩展:Quick Query FeiFeiYeChuan CSDN Blogs,然后输入内容,即可在FeiFeiYeChuan博客下查找相关技术内容。

在博客的导航栏插入 Tip 按钮,点击按钮,界面中间显示"Quick Redirect To FeiFeiYeChuan"的快速导航。点击即可快速进入博客主页。

插件内容

1、目录
2、manifest.json
json 复制代码
{
    "manifest_version": 3,
    "name":"Quick Query FeiFeiYeChuan CSDN Blogs",
    "version": "1.0.0",
    "icons": {
        "16": "images/icon16.png",
        "32": "images/icon16.png",
        "64": "images/icon16.png"
    },
    "background":{      # background 随浏览器运行
        "service_worker": "service-worker.js",
        "type": "module"
    },
    "permissions":["storage", "alarms"],   # 内存权限和闹钟定时权限
    "minimum_chrome_version": "102",
    "omnibox":{
        "keyword": "fei"   # 使用导航栏,必须用到omnibox。关键字是 fei。
    },
    "host_permissions": ["https://extension-tips.glitch.me/*"],

    "content_scripts": [			# content内容
        {
          "matches": [
            "https://*.csdn.net/*",
            "https://blog.csdn.net/*",
            "https://*/blog.csdn.net/*"
            ],
          "js": ["content.js"]
        }
      ]
}
3、service-worker.js
javascript 复制代码
import './sw-omnibox.js';	// 导入js文件
import './sw-tips.js';

// Save default API suggestions
chrome.runtime.onInstalled.addListener(({ reason }) => {
    console.log("reason:", reason)
    if (reason === 'install') {			// 安装完成插件
      chrome.storage.local.set({
        apiSuggestions: ['Python', 'Django', 'Freeswitch']
      });
      console.log("apiSuggestions:", chrome.storage.local.get("apiSuggestions"))
    }
    
    if (reason === 'update') {			// 更新插件
        chrome.storage.local.set({
          apiSuggestions: ['Python', 'Django', 'Freeswitch']
        });
        console.log("apiSuggestions:", chrome.storage.local.get("apiSuggestions"))
      }
  });
4、sw-omnibox.js
javascript 复制代码
console.log("sw-omnibox.js")

const URL_CHROME_EXTENSIONS_DOC =
  'https://so.csdn.net/so/search?t=blog&u=feifeiyechuan&q=';      // 指定博客下查询内容
const NUMBER_OF_PREVIOUS_SEARCHES = 4;

// Display the suggestions after user starts typing
chrome.omnibox.onInputChanged.addListener(async (input, suggest) => {   // omibox内容改变事件
  await chrome.omnibox.setDefaultSuggestion({
    description: '输入FeiFeiYeChuan关键查询'                  
  });
  const { apiSuggestions } = await chrome.storage.local.get('apiSuggestions');
  console.log("111apiSuggestions:", apiSuggestions)
  const suggestions = apiSuggestions.map((api) => {
    return { content: api, description: `Open CSDN FeiFeiYeChuan.${api}` };
  });
  console.log("222suggestions:", suggestions)
  suggest(suggestions);
});


// Open the reference page of the chosen API
chrome.omnibox.onInputEntered.addListener((input) => {   // omibox回车事件
    console.log("chrome.tabs:", chrome.tabs)
  chrome.tabs.create({ url: URL_CHROME_EXTENSIONS_DOC + input });
  console.log("chrome.tabs:", chrome.tabs)
  // Save the latest keyword
  updateHistory(input);
});

async function updateHistory(input) {  // 更新内存apiSuggestions
    const { apiSuggestions } = await chrome.storage.local.get('apiSuggestions');
    console.log("apiSuggestions:", apiSuggestions)
    apiSuggestions.unshift(input);
    console.log("apiSuggestions:", apiSuggestions)
    apiSuggestions.splice(NUMBER_OF_PREVIOUS_SEARCHES);
    console.log("apiSuggestions:", apiSuggestions)
    return chrome.storage.local.set({ apiSuggestions }); 
  }
5、sw-tips.js
javascript 复制代码
console.log("sw-tips.js")
// Fetch tip & save in storage
const updateTip = async () => {
    const tips = [
        "<p><a href='https://blog.csdn.net/feifeiyechuan'>Quick Redirect To FeiFeiYeChuan</a></p>",
        "<p><a href='https://blog.csdn.net/feifeiyechuan'>Quick Redirect To FeiFeiYeChuan</a></p>",
        "<p><a href='https://blog.csdn.net/feifeiyechuan'>Quick Redirect To FeiFeiYeChuan</a></p>",
        "<p><a href='https://blog.csdn.net/feifeiyechuan'>Quick Redirect To FeiFeiYeChuan</a></p>",
        "<p><a href='https://blog.csdn.net/feifeiyechuan'>Quick Redirect To FeiFeiYeChuan</a></p>",
        "<p><a href='https://blog.csdn.net/feifeiyechuan'>Quick Redirect To FeiFeiYeChuan</a></p>",
        "<p><a href='https://blog.csdn.net/feifeiyechuan'>Quick Redirect To FeiFeiYeChuan</a></p>",
    ];
    const randomIndex = Math.floor(Math.random() * tips.length);
    return chrome.storage.local.set({ tip: tips[randomIndex] });
  };
  
  const ALARM_NAME = 'tip';
  
  // Check if alarm exists to avoid resetting the timer.
  // The alarm might be removed when the browser session restarts.
  async function createAlarm() {
    const alarm = await chrome.alarms.get(ALARM_NAME);
    if (typeof alarm === 'undefined') {
      chrome.alarms.create(ALARM_NAME, {
        delayInMinutes: 1,
        periodInMinutes: 1440
      });
      updateTip();
    }
  }
  chrome.alarms.clearAll()
  
  createAlarm();
  
  // Update tip once a day
  chrome.alarms.onAlarm.addListener(updateTip);


  // Send tip to content script via messaging
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {   // 接受content         
    if (message.greeting === 'tip') {
        console.log("chrome.storage.local.get('tip'):", chrome.storage.local.get('tip'))
      chrome.storage.local.get('tip').then(sendResponse);
      return true;
    }
  });
6、content.js
javascript 复制代码
(async () => {
    // Sends a message to the service worker and receives a tip in response
    const { tip } = await chrome.runtime.sendMessage({ greeting: 'tip' });
  
    const nav1 = document.querySelector('.toolbar-container-left');
    const vip = document.querySelector('.toolbar-btn-vip');
    const nav = nav1? nav1: vip;
    
    const tipWidget = createDomElement(`
      <button type="button" popovertarget="tip-popover" popovertargetaction="show" style="padding: 0 12px; height: 36px;background:red;line-height:36px;">
        <span style="display: block; font: var(--devsite-link-font,500 14px/20px var(--devsite-primary-font-family));">Tip</span>
      </button>
    `);
  
    const popover = createDomElement(
      `<div id='tip-popover' popover style="margin: auto;">${tip}</div>`
    );
  
    document.body.append(popover);
    nav.append(tipWidget);
  })();
  
  function createDomElement(html) {
    const dom = new DOMParser().parseFromString(html, 'text/html');
    return dom.body.firstElementChild;
  }
相关推荐
不会敲代码15 小时前
手写 Mini React:从 JSX 到虚拟 DOM 再到 render,搞懂 React 底层原理
前端·javascript·react.js
kyriewen6 小时前
你的代码仓库变成“毛线团”了?Monorepo 用 Turborepo 拆成“乐高积木”
前端·javascript·面试
身如柳絮随风扬6 小时前
你知道什么是 Ajax 吗?—— 从入门到原理,一篇彻底搞懂
前端·ajax·okhttp
旷世奇才李先生7 小时前
Vue3\+TypeScript 2026实战——企业级前端项目架构搭建与性能优化全指南
前端·架构·typescript
Beginner x_u7 小时前
前端八股整理(工程化 02)|CommonJS/ESM、Webpack Loader/Plugin 与Vite 对比
前端·webpack·node.js·plugin·loader
openKaka_8 小时前
createRoot 到底创建了什么:FiberRootNode 和 HostRootFiber 的初始化过程
前端·javascript·react.js
习明然8 小时前
UniApp开发体验感受总结
前端·uni-app
刀法如飞9 小时前
Claude Code Skills 推荐:2026年最值得安装的10个AI技能
前端·后端·ai编程
Lee川10 小时前
面试手写 KeepAlive:React 组件缓存的实现原理
前端·react.js·面试
墨染天姬10 小时前
【AI】cursor提示词小技巧
前端·数据库·人工智能