Back to Amphtml

AMP Viewer API

extensions/amp-viewer-integration/amp-doc-viewer-api.md

latest31.0 KB
Original Source

AMP Viewer API

Introduction

This document explains the API between an AMP Viewer and the AMP document(s) it contains.

API

Initialization

When an AMP Viewer opens an AMP document, it can include initialization parameters. The parameters are set as key value pairs encoded as a query string in the hash fragment of the AMP document URL. For example: www.amp.dev?origin=https%3A%2F%2Fplayground.amp.dev Some parameters are read by the AMP runtime (the core library that initializes and manages all components, included as v0.js) and configure its behavior and others are read by the Viewer integration script in order to establish the communication channel used by the rest of the API. An initialization parameter is enabled or disabled via the '1' or '0' value respectively.

Viewer Integration Script Parameters

Documents served via a cache URL, e.g. cdn.ampproject.org/v/, will include the Viewer integration script. This script adds behavior and enables communication with a parent Viewer.

cap

A comma delimited list of capabilities supported by the Viewer. Other boolean parameters should be deprecated and replaced with an entry in cap.

ParameterSupported messagesDescription
a2aa2aNavigateAMP-to-AMP (A2A) document linking support.
cidcidClient ID service.
errorReportererrorError reporter.
fragmentfragmentURL fragment support for the history API.
handshakepollhandshake-pollMobile web handshake.
iframeScrollViewer platform supports and configures scrolling on the AMP document's iframe.
interceptNavigationnavigateToSupport for navigating to external URLs.
navigateTonavigateToSupport for navigating to external URLs within a native app.
replaceUrlgetReplaceUrlSupport for replacing the document URL with one provided by the Viewer.
swipetouchstart, touchmove, touchendForwards touch events from the document to the Viewer.
viewerRenderTemplateviewerRenderTemplateProxies all mustache template rendering to the Viewer.
xhrInterceptorxhrProxies all XHRs through the Viewer.

origin

The origin of the Viewer. The Viewer Integration will verify this is an allowed domain and this will be the target of all messages sent from the AMP document to the Viewer.

AMP Runtime Parameters

ParameterData typeDescription
cidbooleanWhether to request the Base Client ID from the Viewer.
csibooleanWhether the Viewer will collect latency metrics from the Document.
dialogbooleanWhether the Viewer will take responsibility for opening a dialog for an AMP Access login. If false, opening a login dialog does not involve the Viewer. If true, the Viewer must support openDialog.
developmentbooleanWhether the AMP runtime is in development mode. Development mode will validate the AMP document and show its results in the developer console.
historybooleanWhether the AMP Viewer will take over history management. If true, the Viewer must support popHistory, pushHistory, and historyPopped.
logbooleanWhether to turn on logging in the AMP runtime.
paddingTopintegerThe paddingTop to apply to the document body in pixels. This is used to allow space for a title bar.
p2rbooleanWhether to Pull to Refresh is enabled. pull-to-refresh.js
referrerstringThe referrer to use for AMP analytics.
storagebooleanWhether the Viewer will provide local storage. If true, then the Viewer must support loadStore and saveStore.
viewerUrlstringThe url of the Viewer. This is the shareable Viewer URL and may be used as a fallback as part of AMP Access.
webviewbooleanWhether the document is being loaded in a WebView instead of an iframe. This will enable "embedded" mode for the document, which is needed for dialog to work.
highlightstringThe information to highlight text. JSON-encoded string.
visibilityStateinactive,paused,visible,prerender,hidden (deprecated, use inactive)The initial visibility state of the AMP document.<ul><li>prerender- AMP document is being pre-rendered before being shown. It may be prerendered.</li><li>inactive or hidden -The document is not visible to the user.</li><li>paused - this document should stop loading new resources and pause any resources such as video. The document may still be visible to the user, but the Viewer may be performing a performance sensitive operation such as a swipe.</li><li>visible- The document is active and visible to the user.</li>

Messaging

The AMP Viewer and AMP document communicate via postMessage.

Viewer Integration Messages

The messages in this section are sent by the Viewer Integration Script and are not used by the AMP runtime.

Document to Viewer

MessageDescriptionRequestResponse
channelOpenThis message is sent from the AMP document to the Viewer to tell it that the document is ready to receive messages.{}boolean
touchstart, touchmove, and touchendThese three messages are sent by the Viewer Integration Script to the Viewer and proxy touch events in the iframe.Object (A copy of a browser TouchEvent.)undefined
unloadedThis message is sent in response to a window unloaded event in the document. The Viewer can use this to display an error if an unexpected unload occurs.trueundefined

AMP Runtime Messages

Document to Viewer

MessageDescriptionRequestResponse
broadcastMessage that will be broadcast to every other AMP document open in the Viewer.*(Any value may be broadcast.)Array<*> (The response is an array of the responses from the other documents.)
bindReadySent from AMP pages that use the amp-bind extension. Informs the Viewer that amp-bind has completed initialization.undefinedundefined
cancelFullOverlayRequests that Full Overlay mode is cancelled. If the header was hidden, it should be restored.undefinedundefined (The response is sent once Viewer exits Full Overlay mode.)
cidRequests the scoped Client ID. See Client identifiers in AMP.undefinedstring (The scoped Client ID.)
documentHeightThe AMP runtime sends this request to the Viewer when the height of the document content changes.{'height': (number)}undefined
documentLoadedThe AMP runtime sends this request to the Viewer when it has fully loaded and is ready for display.{'linkRels': (Map<string, string|Array<string>>), 'viewport': (string), 'title': (string), 'sourceUrl': (string), 'isStory': (boolean)}, where linkRels is a map <link> rel values to hrefs.undefined
loadStoreRequests the local storage blob for the document's origin.{'origin': (string)}{'blob': (string)}
openDialogRequests that the AMP Access dialog with a specified URL is opened by the Viewer.{'url': (string)}string (The response is the token string from the dialog if the flow completed successfully. If the dialog is closed without completing the flow, then the response is rejected.)
popHistoryRequests that an entry is popped off the history stack down to the new stackIndex value.{'stackIndex': (string)} (stackIndex specifies the new stack index.)undefined (The response resolves once the history pop is complete.)
prerenderCompleteNotifies the Viewer that prerendering of viewport is complete.undefinedundefined
pushHistoryPushes the new stack index onto the history stack.{'stackIndex': (string)} (stackIndex specifies the new stack index.)undefined (The response resolves once the history pop is complete. It rejects on an invalid stack index.)
replaceHistoryReplaces the fragment value in history state (without pushing or popping).{'fragment': (string)} (fragment specifies the new fragment (hash) value in the current history frame.)undefined (The response resolves once the replacement is complete.)
requestFullOverlayRequests that the Viewer enter Full Overlay mode. In this mode, the title bar may be hidden.undefinedundefined (The response is resolved once Viewer enters Full Overlay mode.)
saveStoreRequests that the specified blob is stored to local storage for the document's origin.{'origin': (string), 'blob': (string)}undefined (The response resolves once the blob has been successfully stored.)
sendCsiRequests that the CSI ticks are flushed. See tick.undefinedundefined
setFlushParamsSets arbitrary additional parameters to be included in the CSI flush. See sendCsi.Objectundefined
tickRecords a timing measurement.{'label': (string), 'from': (string), 'value': (number)}, where from is the label of another tick using this timing reference and value is the time to record.undefined

Viewer to Document

MessageDescriptionRequestResponse
broadcastForwards a broadcasted message received by the Viewer.*(Any value may be broadcast.)*(Any value may be returned.)
historyPoppedThis informs the document that the history stack has been popped down to the new index.{'newStackIndex': (number)}undefined
scrollLockRequests that scrolling should be enabled or disabled in the document by calling preventDefault() on any touchmove events. Requires the swipe capability. Will not stop the user from scrolling using a non-touch input device e.g. mouse/keyboard.booleanundefined
disableScrollRequests that scrolling should be enabled or disabled in the document by setting overflow: hidden on the viewport.booleanundefined
visibilitychangeNotifies the document that its visibility state has changed.{'state': (string)}undefined
willLikelyUnloadNotifies the document that it is likely that it will be imminently unloaded, but it may not be.{}undefined
xhrNotifies the document that an XHR fires.{'input': (string), 'init': (!FetchInitDef)}{'response': (JsonObject|string|undefined)}
viewerRenderTemplateNotifies the document that an XHR fires along with mustache template(s) to render the third party endpoint response.{'originalRequest': {'input': (string), 'init': (!FetchInitDef)}, 'ampComponent': {'type': (string), 'successTemplate': {'type': (string), 'payload': (string)}, 'errorTemplate': {'type': (string), 'payload': (string)}}}{'html': (string), 'response': (JsonObject|string|undefined)}
highlightDismissNotifies the document that users selected to dismiss text highlighting by interacting UI on the Viewer.{}undefined
highlightShownNotifies the Viewer that text highlighting is displayed in the document.{}undefined