gpt4 book ai didi

javascript - 使用 React 通过 chrome 扩展更改已存在页面上的内容

转载 作者:行者123 更新时间:2023-12-03 01:07:00 24 4
gpt4 key购买 nike

我刚刚开始学习 React,并尝试使用它创建一个 chrome 扩展。我正在尝试创建一个带有按钮的扩展程序,其 onClick 将突出显示网页上的某些给定单词。我能够突出显示我向页面介绍的内容中的单词,但不能突出显示页面上已存在的内容中的单词

这是我想出的代码-

弹出 HTML 上有一个带有 highlight-hazardous-words 类的按钮

popup.js(扩展弹出窗口):

window.onload = () => {
const $highlightHazardousButton = document.querySelector('.highlight-hazardous-words');

$highlightHazardousButton.onclick = () => {
// Get active tab
chrome.tabs.query({
active: true,
currentWindow: true,
}, (tabs) => {
// Send message to script file
chrome.tabs.sendMessage(
tabs[0].id,
{ injectApp: true },
response => window.close()
);
});
};
};

main.js(主要 react 应用内容位于此处):

import React from 'react';
import ReactDOM from 'react-dom';
import Highlighter from "react-highlight-words"

class HighlightHazardous extends React.Component {
constructor(props) {
super(props);
this.state = {searchWords : this.props.searchWords, textToHighlight : this.props.textToHighlight}
}

render() {
return (
<Highlighter
highlightClassName="highlighted-text"
searchWords = {this.state.searchWords}
autoEscape = {true}
textToHighlight = {document.body.innerText}
/>
)
}
}
// Message Listener function
chrome.runtime.onMessage.addListener((request, sender, response) => {
// If message is injectApp
if(request.injectApp) {
// Inject our app to DOM and send response
injectApp();
response({
startedExtension: true,
});
}
});

function injectApp() {
const newDiv = document.createElement("div");
newDiv.setAttribute("id", "chromeExtensionReactApp");
document.body.appendChild(newDiv);
ReactDOM.render(<HighlightHazardous searchWords={['hazardous', 'alcoholic']}/>, newDiv);
}

这里附加的 newDiv 突出显示了整个页面主体的单词,我想突出显示任何网页上任何地方而不是新 div 中存在的危险或酒精,基本上,我不想注入(inject)这个新 div 并更改内容页面已存在。

最佳答案

访问网页 DOM 内容的唯一方法是使用 Content Scripts 组件,其中 Chrome 扩展 使用内容脚本来提及 中的 JS 和 CSS 文件>manifest.json,需要注入(inject)底层页面。

如下所述:

The problem with our create-react-app is that the build step will generate the output JS file in different name each time (if the content changed). So we have no way to know the actual file name of the JS file, hence we can’t mention it in our manifest.json file.

解决方法是退出 create-react-app 并手动修改 webpack 配置,为内容脚本创建单独的入口点。

来源:

关于javascript - 使用 React 通过 chrome 扩展更改已存在页面上的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52352198/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com