postMessage API
该框架内置了 postMessage API,可用于与另一个窗口内的演示文稿进行通信。以下示例展示了如何在给定窗口中创建 reveal.js 实例并继续播放幻灯片 2:
¥The framework has a built-in postMessage API that can be used when communicating with a presentation inside of another window. Here's an example showing how you'd make a reveal.js instance in the given window proceed to slide 2:
<window>.postMessage( JSON.stringify({ method: 'slide', args: [ 2 ] }), '*' );
postMessage 事件
¥postMessage Events
当 reveal.js 在 iframe 中运行时,它可以选择将其所有事件冒泡到父级。冒泡事件是包含三个字段的字符串化 JSON:命名空间、事件名称和状态。以下是如何从父窗口订阅它们:
¥When reveal.js runs inside of an iframe it can optionally bubble all of its events to the parent. Bubbled events are stringified JSON with three fields: namespace, eventName and state. Here's how you subscribe to them from the parent window:
window.addEventListener('message', (event) => {
var data = JSON.parse(event.data);
if (data.namespace === 'reveal' && data.eventName === 'slidechanged') {
// Slide changed, see data.state for slide number
}
});
postMessage 回调
¥postMessage Callbacks
当你通过 postMessage API 调用任何方法时,reveal.js 都会发送一条带有返回值的消息。这样做是为了调用 getter 方法并查看结果。查看此示例:
¥When you call any method via the postMessage API, reveal.js will dispatch a message with the return value. This is done so that you can call a getter method and see what the result is. Check out this example:
<revealWindow>.postMessage( JSON.stringify({ method: 'getTotalSlides' }), '*' );
window.addEventListener( 'message', event => {
var data = JSON.parse( event.data );
// `data.method`` is the method that we invoked
if( data.namespace === 'reveal' && data.eventName === 'callback' && data.method === 'getTotalSlides' ) {
data.result // = the total number of slides
}
} );
打开/关闭 postMessage
¥Turning postMessage on/off
可以使用配置标志来打开或关闭此跨窗口消息传递。这些是默认值。
¥This cross-window messaging can be toggled on or off using configuration flags. These are the default values.
Reveal.initialize({
// Exposes the reveal.js API through window.postMessage
postMessage: true,
// Dispatches all reveal.js events to the parent window through postMessage
postMessageEvents: false
});