如何在网页顶部显示自定义 JSX 以进行 Web 扩展

问题描述 投票:0回答:1

我正在使用这个样板代码https://github.com/Jonghakseo/chrome-extension-boilerplate-react-vite。 用例是,如果用户单击与 Web 扩展关联的上下文菜单,它应该在当前网页上打开一个 JSX 模式。

背景.ts

import reloadOnUpdate from 'virtual:reload-on-update-in-background-script';
import 'webextension-polyfill';

reloadOnUpdate('pages/background');

/**
 * Extension reloading is necessary because the browser automatically caches the css.
 * If you do not use the css of the content script, please delete it.
 */
reloadOnUpdate('pages/content/style.scss');

chrome.runtime.onInstalled.addListener(() => {
  console.log('onInstalled....');

  chrome.contextMenus.create({
    id: 'typelessPopup',
    title: 'Add to typless',
    contexts: ['selection'],
  });
  chrome.contextMenus.onClicked.addListener((info, tab) => {
    chrome.storage.local.set({ selectedText: info.selectionText });
   });
});

console.log('background loaded', chrome);

根据样板代码我必须进行哪些代码更改?

javascript html reactjs google-chrome-extension
1个回答
0
投票

要在当前页面上显示自定义模式作为对上下文菜单单击的反应,您需要

  1. 将内容脚本插入页面。这可以通过直接在清单中指定内容脚本和关联的 URL 来完成,或者在用户单击上下文菜单项时使用 chrome.scripting.executeScript API 来完成。在清单中指定它会更容易实现,但这取决于您的扩展。
  2. 在您的内容脚本中,您需要附加消息侦听器,它将侦听特定消息并在此类消息到达时打开模式。
  3. 用户单击上下文菜单项后,您将需要注入内容脚本(如果您没有事先将其添加到清单中)。然后您使用选定的文本将消息发送到当前选项卡。
  4. 在内容脚本中,这将触发消息处理程序,您可以在其中将模式注入页面。如何执行此操作取决于您用于 UI 的库。如果是 React,你可以使用像 inject-react-anywhere 这样的库,它会让事情变得更容易。或者你可以在没有库的情况下使用react-dom中的
    createRoot
    函数
    来实现,在那里渲染你的模态并将根附加到页面。
© www.soinside.com 2019 - 2024. All rights reserved.