Javascript 如何使用ReactJS在Chrome扩展中执行document.write突出显示的文本
我目前正在构建一个简单的扩展,可以检索chrome页面中突出显示的文本,然后使用以下代码在iframe中记录突出显示的文本: popup.html manifest.json 这些代码成功地复制了突出显示的文本,并在给定大小的iframe上写入这些文本 但是,我想在chrome扩展中使用react.js复制相同的功能,因此在执行Javascript 如何使用ReactJS在Chrome扩展中执行document.write突出显示的文本,javascript,reactjs,google-chrome-extension,Javascript,Reactjs,Google Chrome Extension,我目前正在构建一个简单的扩展,可以检索chrome页面中突出显示的文本,然后使用以下代码在iframe中记录突出显示的文本: popup.html manifest.json 这些代码成功地复制了突出显示的文本,并在给定大小的iframe上写入这些文本 但是,我想在chrome扩展中使用react.js复制相同的功能,因此在执行npx react create app项目后,我尝试了项目dir中的以下代码 manifest.json App.js import React,{Component}
npx react create app项目后,我尝试了项目
dir中的以下代码
manifest.json
App.js
import React,{Component}来自'React';
功能Iframe(道具){
返回();
}
常量iframe='';
类应用程序扩展组件{
建造师(道具){
超级(道具);
}
获取_highlight(){
/*全球铬*/
chrome.tabs.executeScript({
代码:“window.getSelection().toString();”
},功能(选择){
document.write(选择[0])
});
}
render(){
返回(
{this.get_highlight()}
);
}
}
导出默认应用程序;
它以某种方式成功构建了iframe,并以给定的大小很好地呈现了iframe,但是,它无法复制高亮显示的文本
哪种修改可以以最简洁的方式解决问题?因为扩展API是异步的,所以使用document.write没有什么意义,因为此时文档(页面)已经关闭。您应该使用标准的DOM方法来处理和分配某些元素的innerHTML。@wOxxOm但是如果是第一个版本,非react-one,每当我更改突出显示的区域并点击扩展名favicon时,请继续写入突出显示的文本。我想知道如何在每次点击favicon时检索突出显示的文本区域,而不是自动跟踪突出显示的文本区域。我的观点是不应该使用document.write。实际上,它的用例完全是针对遗留的黑客和怪癖。@wOxxOm从不使用危险的LysetinerHTML?安全性方面,我也会在iframe上使用sandbox
属性。
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<style>
body {
width: 400px;
height: 500px;
}
iframe {
width: 400px;
height: 500px;
}
</style>
</head>
<body>
<iframe frameborder="1"></iframe> <!--'1' for border on/ '0' for border off-->
<script type="text/javascript" src="popup.js"></script>
</body>
</html>
chrome.tabs.executeScript( {
code: "window.getSelection().toString();"
}, function(selection) {
document.write(selection[0])
});
{
"manifest_version": 2,
"name": "txls_demo",
"description": "retrieve highlighted text then return the summarized result",
"version": "1.0.0",
"icons": {
"16": "favicon.png",
"48": "favicon.png",
"128": "favicon.png"
},
"permissions": [
"activeTab"
],
"browser_action": {
"default_icon": "favicon.png",
"default_popup": "popup.html"
}
}
"name": "txls_demo",
"manifest_version": 2,
"browser_action": {
"default_popup": "index.html",
"default_icon": "favicon.png"
},
"permissions": [
"activeTab"
],
"version": "1.0"
}
import React, { Component } from 'react';
function Iframe(props) {
return (<div dangerouslySetInnerHTML={ {__html: props.iframe?props.iframe:""}} />);
}
const iframe = '<iframe frameborder="1" width="400" height="500"></iframe>';
class App extends Component {
constructor(props) {
super(props);
}
get_highlight() {
/*global chrome*/
chrome.tabs.executeScript( {
code: "window.getSelection().toString();"
}, function(selection) {
document.write(selection[0])
});
}
render() {
return (
<div className="App">
<Iframe iframe={iframe} />
{this.get_highlight()}
</div>
);
}
}
export default App;