【发布时间】:2018-09-12 14:12:01
【问题描述】:
赏金更新
我目前在 iframe 中使用 src="url" 来加载 ReactApp 对我来说不是最佳选择,因为这将允许用户右键单击并“打开 在新窗口中”。
我正在寻找的最佳解决方案是编写我的 bundle.js 与一个或类似的解决方案一起进入 iframe。 src 将保持空白,因此用户无法方便地右键单击 在新窗口/标签中打开。
我正在探索如何使用 React 来制作一个可嵌入的小部件,所以我从谷歌搜索中得到了以下信息。但是,my 不呈现,并返回以下消息。
错误信息 [错误] Invariant Violation:目标容器不是 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')
)
App.js
import React, { Component } from 'react';
class App extends Component {
render() {
return (
<div>This is an embedable widget</div>
)
}
}
export default App;
我创建了一个 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();
现在在远程站点上,我只在标头中有以下脚本来调用上面的 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>
现在是这个……
- test.js 加载成功
- div 创建成功
- iframe 创建成功
- 我可以看到在 iframe 的标头中添加了 bundle.js 以及 id 为 root 的 div
但是,不显示。
感谢有人可以带我进入下一步。我正在使用 create-react-app 创建我的反应文件(这是我学习的唯一方法。)
【问题讨论】:
-
我以后有时间也许可以帮忙。
-
如果您还需要帮助?
-
我现在只是将 react 应用页面设置为 src。不确定这是否是正确的方法。我必须找到隐藏网址的方法,以便网页只能在 iframe 中加载
-
@Eduard 显然,我添加 src 的解决方案有一个缺点,就是让用户可以方便地在新窗口中打开应用程序,这是我们想要避免的。任何解决方案表示赞赏。添加赏金。
-
为什么在新窗口中打开不好,特别是如果用户必须右键单击并从菜单中明确选择它?
标签: javascript reactjs widget