【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;
  }
相关推荐
F-2H1 小时前
C语言:指针4(常量指针和指针常量及动态内存分配)
java·linux·c语言·开发语言·前端·c++
gqkmiss2 小时前
Chrome 浏览器插件获取网页 iframe 中的 window 对象
前端·chrome·iframe·postmessage·chrome 插件
m0_748247554 小时前
Web 应用项目开发全流程解析与实战经验分享
开发语言·前端·php
m0_748255025 小时前
前端常用算法集合
前端·算法
真的很上进5 小时前
如何借助 Babel+TS+ESLint 构建现代 JS 工程环境?
java·前端·javascript·css·react.js·vue·html
web130933203985 小时前
vue elementUI form组件动态添加el-form-item并且动态添加rules必填项校验方法
前端·vue.js·elementui
NiNg_1_2345 小时前
Echarts连接数据库,实时绘制图表详解
前端·数据库·echarts
如若1236 小时前
对文件内的文件名生成目录,方便查阅
java·前端·python
滚雪球~7 小时前
npm error code ETIMEDOUT
前端·npm·node.js
沙漏无语7 小时前
npm : 无法加载文件 D:\Nodejs\node_global\npm.ps1,因为在此系统上禁止运行脚本
前端·npm·node.js