简体   繁体   English

使用纯 JavaScript/JQuery 对 iframe 进行前后控制

[英]Back and Forward Control for an iframe using pure JavaScript/JQuery

I need to create a tightly controlled environment for opening certain pages that need back and forward navigation controls.我需要创建一个严格控制的环境来打开需要后退和前进导航控件的某些页面。 I had poked around on here and found this question and tried to implement it, but I'm having a problem.我在这里闲逛并找到了这个问题并试图实施它,但我遇到了问题。

I have the following for the HTML and Javascript going on, assume it's already styled (reusing code from previous project), and JQuery is already listed in the <head></head> tags:对于 HTML 和 Javascript,我有以下内容,假设它已经样式化(重用以前项目中的代码),并且 JQuery 已经列在<head></head>标签中:

<body>
    <div id="header">
        <div id="shortcutbar">
            <a id="backBtn" onclick =="iframeBack();"></a>
            <a id="forwardBtn" onclick =="iframeForward();"></a>
        </div>
    </div>
    
    <div id="displayContainer">
        <iframe id="display" src="https://website.goes.here/">
        </iframe>
    </div>

    <script>
        function iframeBack() {
            $("#display").contentWindow.history.go(-1);
        }
        function iframeForward() {
            $("#display").contentWindow.history.go(1);
        }
    </script>
</body>

Checking the console, I get the following error: Uncaught TypeError: Cannot read property "history" of undefined and it gives both whatever line the function is called in the HTML, and the line of the function itself in the script tags.检查控制台,我收到以下错误: Uncaught TypeError: Cannot read property "history" of undefined错误: Uncaught TypeError: Cannot read property "history" of undefined它给出了在 HTML 中调用函数的任何行,以及脚本标签中函数本身的行。

I'm at a loss of what isn't working, as everything I've found thus far just refers to some variation of what I've already typed.我不知道什么不起作用,因为到目前为止我发现的一切都只是指我已经输入的内容的一些变化。

The jQuery object doesn't have contentWindow property. jQuery 对象没有contentWindow属性。

You need the underlying element ... $("#display")[0].contentWindow .您需要底层元素 ... $("#display")[0].contentWindow

With that said if the iframe source is from a different origin than the main page you are security restricted from accessing the frame window using javascript话虽如此,如果 iframe 源来自与主页不同的来源,您将受到安全限制,无法使用 javascript 访问框架窗口

You can use postMessage also for secure communication您也可以使用 postMessage 进行安全通信

$("#display").contentWindow.postMessage('back');
window.addEventListener('message', ({ data }) => {
  data === "back" && window.history.back()
});

https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM