iframe中的后退和前进按钮

ran*_*dev 25 javascript iframe

如何用JS"实现"iframe中的后退和前进按钮?

And*_*y E 38

使用该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();
Run Code Online (Sandbox Code Playgroud)

要么

iframe.contentWindow.history.go(-1); // back
iframe.contentWindow.history.go(1);  // forward
Run Code Online (Sandbox Code Playgroud)

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

  • 这里的丑陋问题是,当你的iframe已经在它自己的历史开始时 - 并且无法在脚本中检测到这种情况 - 做另一个back()将有效地触发包含页面上的back(),这是几乎肯定不是你想要的.在我迄今为止测试过的所有浏览器中都是如此; Chrome 31.0.1650.57,Firefox 24,IE7 ...... (11认同)
  • 谈论丑陋,为了防止在iframe窗口的开始按下后退按钮,你可以在iframe加载和禁用后退按钮时添加一个变量"history = 0".转发历史记录+ 1,返回历史记录-1. (4认同)
  • 如果 iframe 是沙盒的(即指向与包含页面不同的服务器),那么这不起作用。 (2认同)
  • 您还可以使用侦听器(或更丑陋的解决方案)从iframe获取所有访问过的网址,将它们存储在数组中,然后手动实现后退和前进按钮,这些按钮会根据上/下一项更改iframe SRC(如果定义)在数组中 (2认同)

Pav*_*hov 8

框内按钮:

<input type="button" value="Back" onclick="history.back()">
Run Code Online (Sandbox Code Playgroud)

父框架内的按钮:

<input type="button" value="Back" onclick="frame_name.history.back()">
Run Code Online (Sandbox Code Playgroud)


Ada*_*ett 8

2017年更新:如果iframe内容的来源与封闭页面的来源不同,则无法做任何事情 - 除非您控制远程来源的内容并且可以让它接受postMessage事件.如果原点相同,则较旧的答案仍然有效.