在Chrome扩展程序中将React Component注入页面的正确方法?

编程入门 行业动态 更新时间:2024-10-24 02:02:44
本文介绍了在Chrome扩展程序中将React Component注入页面的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在制作一个Chrome扩展程序,我想使用内容脚本将HTML注入到页面DOM中.这很容易,但是我也希望内容脚本是一个React组件,并且JS本身不需要与页面JavaScript上下文进行交互,因此使其更简单.我有一种简单的方法可以将容器元素注入到我的React代码可以渲染到的DOM中,但是我觉得它很hacky,所以我想知道React开发人员是否可以建议一种正式的方式(Google并不是特别推荐在此特定问题上很有用).

I am making a Chrome Extension and I want to inject HTML into the page DOM using the content scripts. That is easy, but I also want the content script to be a React component and the JS itself does not need to interact with the page JavaScript context, so that makes it simpler. I have a simple way to inject a container element into the DOM that my React code can render to, but I feel like it is very hacky and so I was wondering if there was an official way that React developers could suggest (Google was not particularly useful on this specific matter).

import React from 'react'; import ReactDOM from 'react-dom'; class App extends React.Component { render() { return <h1>App was injected.</h1> } }; let container = document.createElement('div'); container.setAttribute("id", "app-wrapper"); document.body.appendChild($el); ReactDOM.render( <App/>, container);

推荐答案

通常,它分为2个文件,一个HTML和一个JS.像这样:

Usually it's split into 2 files, one HTML and one JS. Something like this:

index.html

index.html

<head> <script src="path/to/bundle.js"></script> </head> <body> <div id="app-wrapper" /> </body>

App.js

import React from 'react'; import ReactDOM from 'react-dom'; class App extends React.Component { render() { return <h1>App was injected.</h1> } }; ReactDOM.render( <App/>, document.getElementById("app-wrapper"));

我不知道官方的方式,但这是在create-react-app和大多数教程中找到的实现.

I don't know about an official way, but this is the implementation found in create-react-app and most of tutorials around.

更多推荐

在Chrome扩展程序中将React Component注入页面的正确方法?

本文发布于:2023-11-16 20:46:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1607401.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中将   正确   页面   程序   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!