关于chrome-extension:一个可以跳转GitHub项目package引入包地址的插件

地址

插件github地址

形容

有时候逛github看他人我的项目的时候,想看看他们的package外面援用了什么包,不晓得这些包是干什么的。复制再去搜寻感觉有点麻烦,就想实现一个chrome插件点击包名的时候能跳转到对应的github地址、npm地址或者google搜寻。兴许曾经有插件实现了,懒得去找了,简略的实现一下并不难,也不便当前本人加性能。

实现

  • 配置manifest.json

content_scripts的matches属性设置在遇到什么url的时候去执行js脚本,content-script.js既是须要执行的脚本。

popup.html是插件点击后的弹窗,配置一下插件名和形容,增加插件icon。ok,其余的临时不须要。

{
  "name": "PKG-URL",
  "description": "Get url of the github project's package.",
  "version": "1.0",
  "manifest_version": 3,
  "content_scripts": [
    {
      "matches": ["https://github.com/*/*"],
      "js": ["content-script.js"]
    }
  ],
  "action": {
    "default_popup": "popup.html"
  },
  "icons": {
    "16": "/imgs/logo.png",
    "32": "/imgs/logo.png",
    "48": "/imgs/logo.png",
    "128": "/imgs/logo.png"
  }
}

实现逻辑

按情理这些class应该不会变的,获取package.json外面的所有包名的dom,给他们增加点击事件,点击时候弹窗显示npm/github/google选项,到对应的地址。

const highlight = document.querySelector(".highlight");
const allBlobCode = highlight.querySelectorAll("tr td.blob-code");
const allPkg = handle([...allBlobCode]);
const ToolDom = createToolDom();
let searchKey = "";

allPkg.forEach((item) => {
  item.style.cursor = "pointer";
  item.title = "点击可跳转";
  item.addEventListener("click", () => {
    searchKey = item.innerText.replace(/\"/g, "");
    item.parentElement.appendChild(ToolDom);
  });
});

解决一下dom,因为它package.json外面的每一行都是tr td包裹的。这里筛选一下,只对 dependenciesdevDependencies 上面的dom增加点击事件,其它的临时不论。

function handle(allBlobCode) {
  function filterPkg(allPkg, key) {
    const index = allPkg.findIndex((item) => {
      const ent = item.querySelector("span.pl-ent");
      return ent && ent.innerText === key;
    });
    const pkgs = index !== -1 ? allPkg.slice(index + 1) : [];
    const end = pkgs.findIndex((v) => v.innerText.includes("}"));
    return end !== 1 ? pkgs.slice(0, end) : pkgs;
  }
  const depPkg = filterPkg(allBlobCode, '"dependencies"');
  const devPkg = filterPkg(allBlobCode, '"devDependencies"');
  return [...depPkg, ...devPkg].map(
    (el) => el.querySelector("span.pl-ent") || el
  );
}

createToolDom函数就是去创立咱们的弹窗dom,不晓得能不能写html和css的模式来引入,这里懒得去看文档了,当前再钻研。先间接js创立了,反正代码也不多;都是一些设置dom款式的呆呆代码,就不贴了,具体能够去github地址看源码。

先间接去搜寻吧,跳转的官网略微麻烦了点。原本想间接去搜寻后果第一个,然而第一个也不肯定是官网,先这样了。也不便一些了,省得还要复制再开网页搜寻。

btn.addEventListener("click", () => {
      if (!searchKey) return;
      const url = {
        npm: `https://www.npmjs.com/search?q=${searchKey}`,
        github: `https://github.com/search?q=${searchKey}`,
        google: `https://www.google.com/search?q=${searchKey}`,
      };
      window.open(url[value]);
    });Ï

成果

OK,这样就实现了,略微在popup.html外面写点介绍。

挪动到包名下面会提醒能够点击,指针也会变成小手指,点击就会弹窗抉择到对应的地址去。

总结

简略的做一些性能还是挺简略的(如同是句废话哈哈哈),公布插件如同要花钱,懒得搞了,本地用用算了。想用的小伙伴能够去github地址下载自行引入。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理