Som*_*ial 7 javascript widget reactjs
更新为Bounty
我目前在我的iframe中使用src ="url"来加载对我来说不是最佳的ReactApp,因为这将允许用户右键单击并"在新窗口中打开".
我正在寻找的最佳解决方案是将我的bundle.js与一个或类似的解决方案一起写入iframe.src将保持为空白,因此用户无法在新窗口/选项卡中右键单击以打开.
我正在探索如何使用React制作一个可嵌入的小部件,所以我到目前为止从google搜索到了以下内容.但是,我不渲染,并返回以下消息.
错误消息 [错误]不变违规:目标容器不是DOM元素.
我使用create-react-app为我的嵌入式应用程序,我只有2个简单的文件.
index.js
import React from 'react';
import ReactDom from 'react-dom';
import App from './App';
ReactDom.render(
<App />, document.getElementById('root')
)
Run Code Online (Sandbox Code Playgroud)
App.js
import React, { Component } from 'react';
class App extends Component {
render() {
return (
<div>This is an embedable widget</div>
)
}
}
export default App;
Run Code Online (Sandbox Code Playgroud)
我创建了一个test.js,它将在远程iframe中使用下面的简单代码调用以生成html,包含js包,以及包含id的div.
这是test.js
//Creates Div
var d = document.createElement("div");
document.body.appendChild(d);
//Creates iFrame
var n = document.createElement("iframe");
n.id = "microcom-frame";
n.style.width = "100%";
n.style.height = "100%";
n.style.background = "transparent";
n.style.position = "relative";
n.style.margin = 0;
n.style.border = "none";
n.style.overflow ="hidden";
n.style.display = "block";
//Append iFrame inside Div
d.appendChild(n);
//Write content to iFrame
n.contentWindow.document.open("text/html", "replace"),
n.contentWindow.document.write("\n <!doctype html>\n <head><script src='http://localhost:3001/static/js/bundle.js' type='text/javascript'></script></head>\n <body><div id='root'></div></body>\n </html>"),
n.contentWindow.document.close();
Run Code Online (Sandbox Code Playgroud)
现在在远程站点上,我在标题中只有以下脚本来调用上面的test.js.
<script>
(function() {
var d = document,
h = d.getElementsByTagName('head')[0],
s = d.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'http://localhost:3001/test.js';
h.appendChild(s);
} )();
</script>
Run Code Online (Sandbox Code Playgroud)
这是......
但是,没有显示.
感谢有人可以带我到下一步.我正在使用create-react-app创建我的反应文件(这是我学习的唯一方法.)
要满足同源策略(防止 CORS 错误),请设置<iframe>'ssrcdoc属性,而不是尝试write设置它。
n.srcdoc = "\n <!doctype html>\n <head><script src='http://localhost:3001/static/js/bundle.js' type='text/javascript'></script></head>\n <body><div id='root'></div></body>\n </html>";
Run Code Online (Sandbox Code Playgroud)
作为额外的好处,您可以通过以下方式禁用右键单击上下文菜单:
n.contentWindow.document.addEventListener("contextmenu", function(e){
e.preventDefault();
return false;
}, false);
Run Code Online (Sandbox Code Playgroud)
作为一项安全措施,这完全没有用处,但它只是为了转移注意力。当您单独打开框架时显示的页面将不包含内容。仅当 iframe 页面中没有用户想要复制的内容时才执行此操作;这并不能阻止他们这样做,但如果你确实想复制某些东西,那真的很烦人。
演示:
n.srcdoc = "\n <!doctype html>\n <head><script src='http://localhost:3001/static/js/bundle.js' type='text/javascript'></script></head>\n <body><div id='root'></div></body>\n </html>";
Run Code Online (Sandbox Code Playgroud)