【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;
  }
相关推荐
To_OC8 小时前
别再串行写 await 了,Promise.all 才是并行请求的正确打开方式
前端·javascript·promise
vipbic9 小时前
中后台越做越乱后,我用插件化把它救回来了
前端·vue.js
Hyyy9 小时前
Computer Use 适合做什么,不适合做什么——一次真实使用后的思考
前端
小和尚同志9 小时前
前端 AI 单元测试思考与落地
前端·人工智能·aigc
invicinble10 小时前
c端系统,其实更像一个信息展示平台
前端
李姆斯11 小时前
管理是否可以被完全量化
前端·产品经理·团队管理
名字还没想好☜12 小时前
Next.js 中间件实战:鉴权、重定向与 A/B 分流
开发语言·前端·javascript·中间件·react·next.js
广州灵眸科技有限公司12 小时前
瑞芯微RV1126B开发板(EASY-EAI-PI2) INI文件操作
java·前端·javascript·网络·人工智能
江华森13 小时前
Web 开发基础:HTTP 与 REST
前端·网络协议·http
IT_陈寒13 小时前
Redis的KEYS命令把我搞崩溃了,改用SCAN才活过来
前端·人工智能·后端