在Chrome扩展程序中将React Component注入页面的正确方法? [英] Proper way to inject React Component onto page in Chrome Extension?

查看:560
本文介绍了在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注入页面的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆