Skip to content

Commit

Permalink
fix: открытие sidePanel в chromium, инициализация поисковых кнопок
Browse files Browse the repository at this point in the history
  • Loading branch information
ivanmem committed Nov 2, 2024
1 parent 9584fcf commit d1ff05f
Show file tree
Hide file tree
Showing 4 changed files with 135 additions and 127 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
{
"name": "shikimori-search-extension",
"displayName": "Shiki Search",
"version": "1.0.1",
"version": "1.0.2",
"private": true,
"packageManager": "pnpm@9.7.1",
"description": "[description]",
"description": "Расширение для добавления поисковых кнопок на сайте Shikimori",
"scripts": {
"dev": "npm run clear && cross-env NODE_ENV=development run-p dev:*",
"dev-firefox": "npm run clear && cross-env NODE_ENV=development EXTENSION=firefox run-p dev:*",
Expand Down
99 changes: 54 additions & 45 deletions src/background/main.ts
Original file line number Diff line number Diff line change
@@ -1,59 +1,68 @@
import {onMessage, sendMessage} from 'webext-bridge/background'
import type {Tabs} from 'webextension-polyfill'
import { onMessage, sendMessage } from "webext-bridge/background";
import type { Tabs } from "webextension-polyfill";

const isFirefox = navigator.userAgent.includes('Firefox');
const isFirefox = navigator.userAgent.includes("Firefox");

// only on dev mode
if (import.meta.hot) {
// @ts-expect-error for background HMR
import('/@vite/client')
// load latest content script
import('./contentScriptHMR')
// @ts-expect-error for background HMR
import("/@vite/client");
// load latest content script
import("./contentScriptHMR");
}

if (isFirefox) {
// для переключения боковой панели с помощью кнопки действия в хроме:
browser.action.onClicked.addListener(() => {
browser.sidebarAction.toggle()
})
// для переключения боковой панели с помощью кнопки действия в хроме:
browser.action.onClicked.addListener(() => {
browser.sidebarAction.toggle();
});
} else {
// @ts-expect-error missing types
browser.sidePanel
.setPanelBehavior({ openPanelOnActionClick: true })
.catch((error: unknown) => console.error(error));
}

browser.runtime.onInstalled.addListener((): void => {
// eslint-disable-next-line no-console
console.log('Extension installed')
})
// eslint-disable-next-line no-console
console.log("Extension installed");
});

let previousTabId = 0
let previousTabId = 0;

// пример коммуникации: отправьте заголовок предыдущей вкладки с фоновой страницы
// смотрите shim.d.ts
browser.tabs.onActivated.addListener(async ({tabId}) => {
if (!previousTabId) {
previousTabId = tabId
return
}

let tab: Tabs.Tab

try {
tab = await browser.tabs.get(previousTabId)
previousTabId = tabId
} catch {
return
}

sendMessage('tab-prev', {title: tab.title}, {context: 'content-script', tabId})
})

onMessage('get-current-tab', async () => {
try {
const tab = await browser.tabs.get(previousTabId)
return {
title: tab?.title,
}
} catch {
return {
title: undefined,
}
}
})
browser.tabs.onActivated.addListener(async ({ tabId }) => {
if (!previousTabId) {
previousTabId = tabId;
return;
}

let tab: Tabs.Tab;

try {
tab = await browser.tabs.get(previousTabId);
previousTabId = tabId;
} catch {
return;
}

sendMessage(
"tab-prev",
{ title: tab.title },
{ context: "content-script", tabId },
);
});

onMessage("get-current-tab", async () => {
try {
const tab = await browser.tabs.get(previousTabId);
return {
title: tab?.title,
};
} catch {
return {
title: undefined,
};
}
});
10 changes: 6 additions & 4 deletions src/composables/useShikimoriMetaName.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,15 @@ export function useShikimoriMetaName() {
const targetEl = document.querySelector<HTMLDivElement>(
".block:has(.b-external_link), .block.block-shiki-search-extension",
);
if (!targetEl || init) {
const classContains = Boolean(
targetEl?.classList.contains("block-shiki-search-extension"),
);
if (!targetEl || (init && classContains)) {
el.value = targetEl ?? undefined;
return;
}

init = true;

if (!targetEl.classList.contains("block-shiki-search-extension")) {
if (!classContains) {
targetEl.classList.add("block-shiki-search-extension");
}

Expand All @@ -75,6 +76,7 @@ export function useShikimoriMetaName() {
link.remove();
});
el.value = targetEl ?? undefined;
init = true;
}

return { el, metaName };
Expand Down
149 changes: 73 additions & 76 deletions src/manifest.ts
Original file line number Diff line number Diff line change
@@ -1,85 +1,82 @@
import fs from 'fs-extra'
import type {Manifest} from 'webextension-polyfill'
import type PkgType from '../package.json'
import {isDev, isFirefox, port, r} from '../scripts/utils'
import fs from "fs-extra";
import type { Manifest } from "webextension-polyfill";
import type PkgType from "../package.json";
import { isDev, isFirefox, port, r } from "../scripts/utils";

interface WebExtensionChrome {
side_panel?: { default_path: string }
side_panel?: { default_path: string };
}

export async function getManifest() {
const pkg = await fs.readJSON(r('package.json')) as typeof PkgType
const manifest: Manifest.WebExtensionManifest & WebExtensionChrome = {
manifest_version: 3,
name: pkg.displayName || pkg.name,
version: pkg.version,
description: pkg.description,
action: {
default_icon: './assets/icon-512.png',
// default_popup: './dist/popup/index.html',
const pkg = (await fs.readJSON(r("package.json"))) as typeof PkgType;
const manifest: Manifest.WebExtensionManifest & WebExtensionChrome = {
manifest_version: 3,
name: pkg.displayName || pkg.name,
version: pkg.version,
description: pkg.description,
action: {
default_icon: "./assets/icon-512.png",
// default_popup: './dist/popup/index.html',
},
// не работает для chromium
sidebar_action: {
default_panel: "dist/sidepanel/index.html",
open_at_install: true,
},
side_panel: {
default_path: "dist/sidepanel/index.html",
},
// options_ui: {
// page: "./dist/options/index.html",
// open_in_tab: true,
// },
background: isFirefox
? {
scripts: ["dist/background/index.mjs"],
type: "module",
}
: {
service_worker: "./dist/background/index.mjs",
},
// does not work for chromium based
sidebar_action: {
default_panel: 'dist/sidepanel/index.html',
open_at_install: true,
},
side_panel: {
default_path: 'dist/sidepanel/index.html',
},
options_ui: {
page: './dist/options/index.html',
open_in_tab: true,
},
background: isFirefox
? {
scripts: ['dist/background/index.mjs'],
type: 'module',
}
: {
service_worker: './dist/background/index.mjs',
},
icons: {
16: './assets/icon-512.png',
48: './assets/icon-512.png',
128: './assets/icon-512.png',
},
permissions: [
'tabs',
'storage',
'activeTab',
'sidePanel',
],
host_permissions: ['*://*/*'],
content_scripts: [
{
matches: [
'https://*.shikimori.one/*',
],
js: [
'dist/contentScripts/index.global.js',
],
},
],
web_accessible_resources: [
{
resources: ['dist/contentScripts/style.css'],
matches: ['<all_urls>'],
},
],
content_security_policy: {
extension_pages: isDev
// this is required on dev for Vite script to load
? `script-src \'self\' http://localhost:${port}; object-src \'self\'`
: 'script-src \'self\'; object-src \'self\'',
},
}

if (isFirefox) {
delete manifest.side_panel
icons: {
16: "./assets/icon-512.png",
48: "./assets/icon-512.png",
128: "./assets/icon-512.png",
},
permissions: ["tabs", "storage", "activeTab", "sidePanel"],
host_permissions: ["*://*/*"],
content_scripts: [
{
matches: ["https://*.shikimori.one/*"],
js: ["dist/contentScripts/index.global.js"],
},
],
web_accessible_resources: [
{
resources: ["dist/contentScripts/style.css"],
matches: ["<all_urls>"],
},
],
content_security_policy: {
extension_pages: isDev
? // this is required on dev for Vite script to load
`script-src \'self\' http://localhost:${port}; object-src \'self\'`
: "script-src 'self'; object-src 'self'",
},
// не нужно для chromium
browser_specific_settings: {
gecko: {
id: "shikimori-search-extension@example.com",
},
},
};

} else {
delete manifest.sidebar_action
}
if (isFirefox) {
delete manifest.side_panel;
} else {
delete manifest.sidebar_action;
delete manifest.browser_specific_settings;
}

return manifest
return manifest;
}

0 comments on commit d1ff05f

Please sign in to comment.