3

当 HTML 父窗口和 iFrame 内容位于同一 Web 服务器上时,它们相互了解并自由通信。当它们保存到 DVD 时,当 iFrame 尝试将 top 作为本地文件联系时,Chrome 会抛出“不安全的 JavaScript 尝试使用 URL 访问框架”。

下面的catch捕获了权限错误,但是错误仍然被浏览器注册并且对用户可见。

在尝试访问以排除不安全的 JavaScript 错误之前,是否可以先测试是否允许此访问?

           // Called from script in an iframe
           function findSiblingIFrame(sibId) {
                 try {
                       var sibFrame = top.document.getElementById(sibId);
                       if (sibFrame != null) {
                           alert("found sibling iframe");
                       } else {
                           alert("did not find sibling iframe");
                       }
                   }
                   catch (err) {
                      alert("not allowed to find sibling iframe");
                      // Would rather test if permission first to prevent
                      // browser from registering the error.
                   }
           }
4

2 回答 2

0

只需检查window.location.protocol,然后您就可以有不同的行为,无论它是在 Web 服务器 ( http: ) 上还是在本地 ( file: ) 上运行。

您应该知道,尽管不同的浏览器对这些事情有不同的权限,所以您也应该检查用户的浏览器。

于 2012-03-07T00:21:33.990 回答
0

我最终使用 HTML5 消息传递在 iframe 层次结构中上下传递潜在的沙盒请求。

例如,嵌套 iframe 层次结构中的每个 html 页面都可以访问以下 javascript。如果捕获的 HTML5 消息请求无法在本地执行,则将消息传递给父级。父级也可以将消息向下传递到 iframe。这仅适用于所有页面都可以访问相同的 javascript 文件。

// function to handle message request
function messageHandler(argJSON) {
    // A collection of available functions for inbound messages
    var msgFunctionMap = new Object();
    msgFunctionMap.removeBorder = removeBorder;
    msgFunctionMap.restoreBorder = restoreBorder;
    // ...more
    // try execute request
    try {
        var jsonObj = JSON.parse(argJSON.data);
        msgFunctionMap[jsonObj.request](jsonObj.args);
    }
    catch (err) {
        alert(" Request not supported: " + argJSON.data);
    }
};
// example function to remove object id x's border if it exists in "this" window, else pass request up
var removeBorder = function (jsonMsg, argObj) {
    var xiFrame = document.getElementById("x");
    if (xiFrame != null) {
        xiOrigWidth = xiFrame.style.borderWidth;
        xiFrame.style.borderWidth = '0px';
    }
    // Otherwise, pass message up else if (window.parent && window.parent.postMessage) {
        window.parent.postMessage(jsonMsg.data, "*");
    }
};
//... more
// pass predefined message request from child to parent
function messageUpHandler(message) {
    if (window.parent && window.parent.postMessage) {
        window.parent.postMessage(message.data, "*");
    }
};
// Listener for child messages
if (window.addEventListener) {
    window.addEventListener("message", messageUpHandler, true);
}
于 2012-05-08T18:19:07.460 回答