我有一个Polymer应用程序,其中我们需要生成一个带有JSON数据的新选项卡,该选项卡将选项卡发送给支持并获取呈现的HTML作为响应。
我采用的方法是在父窗口中设置一个变量:
window.previewJSON = some_json; //stringified json
接下来是:
window.open("/preview.html");
打开包含代码的预览文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Preview</title>
<script src="/bower_components/jquery/dist/jquery.min.js" type="application/javascript"></script>
</head>
<body>
<div id="content"></div>
<script>
(function () {
var json = window.opener !== null ? window.opener.previewJSON : window.parent.previewJSON;
window.previewJSON = json;
if (!window.sessionStorage.getItem("page_json"))
window.sessionStorage.setItem("page_json", json);
$.ajax({
url: '/api/render/page',
dataType: 'text',
type: 'post',
contentType: 'application/json',
data: window.sessionStorage.getItem("page_json"),
success: function (data) {
$('#content').html(data);
},
error: function (jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}).call(this);
</script>
</body>
</html>
预览选项卡现在可以从父级获取JSON,并且AJAX渲染工作完美。现在我使用Chrome插件响应式网页设计测试人员发现here(使用它的业务要求)在响应式视图中测试预览。此工具会生成一个包含当前URL的新窗口,并尝试加载内容。现在我需要将JSON数据传递给它。
我注意到,在我之前打开的标签中,数据在 window.opener.previewJSON 中可用,而在工具打开的窗口中,它在窗口中。 opener 为null, window.parent.previewJSON 存在,但未定义。
代码
var json = window.opener !== null ? window.opener.previewJSON : window.parent.previewJSON;
window.previewJSON = json;
是出于这个原因。
奇怪的是,如果我将window.parent.previewJSON写为某些常量,例如&#34; Hello&#34;它在插件窗口中可用,但如果我因某种原因使用变量json,那么它是未定义的。
我无法弄清楚为什么会发生这种情况。任何建议都表示赞赏。