window.frameElement is undefined in Google Chrome when local, works when online
本问题已经有最佳答案,请猛点这里访问。
我需要开发一个可在本地和离线访问的Web应用程序。作为设计的一部分,使用iframe可以根据需要交换内容。问题在于,当在本地访问该脚本时,该脚本只能在FF 32和IE 11中运行,而不能在Chrome 38中运行。所有脚本都在64位Windows 7 SP1上运行。
此外,从服务器访问时,相同的脚本可在Chrome,FF和IE中使用。我预感这可能是由Chrome中的错误引起的。不过,我想知道我的脚本是否有问题。我在这里提供了它们:
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <body> <p>This example demonstrates how to assign an"onload" event to an iframe element.</p> <iframe id="iFrame" name="iFrame" height="500px" width="500px" src="about:blank"></iframex> <p id="demo"></p> <button id="swap" onclick="swap()">SWAP</button> function swap() { document.getElementById("iFrame").src ="child.html"; } function myFunction() { document.getElementById("demo").innerHTML ="Iframe is loaded."; } window.onload = myFunction(); </body> |
child.html
1 2 3 4 5 6 7 8 9 | <body> This is an extra page... <button onclick="next()">NEXT</button> <script src="worker.js" type="text/javascript"> </body> |
grandchild.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <body> <h1 id="header"> <button onclick="prev()">PREV</button> window.onload = function () { init(); }; <script src="worker.js"> </body> |
worker.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | function next() { window.frameElement.src ="grandchild.html"; } function prev() { window.frameElement.src ="child.html"; } function init() { var iFrame = window.frameElement; var frameDocument = (iFrame.contentWindow || iFrame.contentDocument); if (frameDocument.document)frameDocument = frameDocument.document; frameDocument.getElementById("header").innerHTML ="This is from the script!!"; } |
很明显,window.frameElement是未定义的。我是Web开发的新手。任何帮助都会感激我。
深入研究之后,我了解到这是Chrome / Chromium的功能。为了安全起见,所有本地内容都会在iframe中被阻止。有两种可能的解决方案:
a)因此,要使用iframe,必须从Web服务器访问内容。这可以通过从服务器[在线]提供整个应用程序或将其作为具有附加功能的Node.js应用程序捆绑在一起来实现。
b)另一种可能的解决方案是用一种可能的替代方法来替换iframe,尽管没有哪一种解决方案比使用iframe(恕我直言)更简单。
由于我的要求是从CD / DVD本地部署此Web应用程序,因此我发现Node.js解决方案很有吸引力,因为这也暗示着可能进行Node-webkit部署。