如何在iframe之外操作历史记录

3

我正在编写一个简单的Angular应用程序,我想做一个类似于浏览器的东西:一个输入框,用户可以在其中输入URL,一个iframe来显示URL的内容,一个按钮,用户可以点击以返回。

我使用$sce来ng-src iframe以接受用户输入的任何网站。但由于CORS问题,无法实现历史记录后退功能。

有没有可能实现它?谢谢

JS

$scope.testurl = $sce.trustAsResourceUrl("http://www.baidu.com");
$scope.backPage = function () {
  var ifr = document.getElementById("myIframe");
  ifr.contentWindow.history.back();
}

HTML

<ion-view view-title="Account">
  <ion-content>
    <div ng-click="backPage()">BACK</div>
    <iframe id="myIframe" style="height:500px;width:100vw" ng-src="{{testurl}}"></iframe>
  </ion-content>
</ion-view>

错误
Error: Blocked a frame with origin "http://localhost:8101" from accessing a cross-origin frame.
    at Error (native)
    at Scope.$scope.backPage (http://localhost:8101/js/controllers.js:32:24)
    at fn (eval at compile (http://localhost:8101/lib/ionic/js/ionic.bundle.js:27638:15), <anonymous>:4:215)
    at http://localhost:8101/lib/ionic/js/ionic.bundle.js:65427:9
    at Scope.$eval (http://localhost:8101/lib/ionic/js/ionic.bundle.js:30395:28)
    at Scope.$apply (http://localhost:8101/lib/ionic/js/ionic.bundle.js:30495:25)
    at HTMLDivElement.<anonymous> (http://localhost:8101/lib/ionic/js/ionic.bundle.js:65426:13)
    at defaultHandlerWrapper (http://localhost:8101/lib/ionic/js/ionic.bundle.js:16787:11)
    at HTMLDivElement.eventHandler (http://localhost:8101/lib/ionic/js/ionic.bundle.js:16775:9)
    at triggerMouseEvent (http://localhost:8101/lib/ionic/js/ionic.bundle.js:2953:7)

可以在这里找到相关讨论和一些问题:https://dev59.com/t3A75IYBdhLWcg3wg5Vh - Gjermund Dahl
2个回答

2
使用 window.history 对象。
// For the current window
window.history.back();     
window.history.forward();

// For an iframe's window
iframe.contentWindow.history.back(); 
iframe.contentWindow.history.forward();

或者

iframe.contentWindow.history.go(-1); // back
iframe.contentWindow.history.go(1);  // forward

https://developer.mozilla.org/en/dom/window.history


1

对于那些不仅作为链接安全跟随的 URL,而且其内容也安全包含在您的应用程序中的 URL。例如 ng-include、src/ngSrc 绑定用于除 IMG(如 IFRAME、OBJECT 等)之外的标签。

请注意,$sce.RESOURCE_URL 对 URL 的声明比 $sce.URL 更强烈,因此需要信任 $sce.RESOURCE_URL 值的上下文可以在任何需要信任 $sce.URL 值的地方使用。

文档

app.config(function($sceDelegateProvider) {
 $sceDelegateProvider.resourceUrlWhitelist([
    // Allow same origin resource loads.
    'self',
    // Allow loading from our assets domain.  Notice the difference between * and **.
    'http://www.baidu.com'
  ]);

  // The blacklist overrides the whitelist so the open redirect here is blocked.
  $sceDelegateProvider.resourceUrlBlacklist([
    'http://myapp.example.com/clickThru**'
  ]);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接