简体   繁体   中英

How can you detect if current page is AMP?

I'm new to AMP and we only want something to happen if the current page is not an AMP page. Is there a universal property on window that we can see if it's defined in order to detect if the current view is AMP or not?

Some background: we're currently delivering a react app through a wordpress plugin and we're noticing some errors that might be from AMP pages only (even though we're not approved to run on AMP pages yet - not sure why our script is still attempting to load), so we'd like to not run our script if the current view is an AMP page.

I ended up seeing that the <html> tag tends to have an attribute amp when it's an AMP page. I'm not sure if it's always the case, but if anyone has the same question, this seems to work for my use-case: document.getElementsByTagName('html')[0].hasAttribute('amp')

There is the "AMP" property after the initialization of the AMP page. This test is more accurate than merely checking for the amp markup.

Beware that adding any custom javascript to do such detections will invalidate the AMP page. The page may still function on its own but will not be able to exploit the AMP-cache or search engine enhancements.

Not on window , but the AMP spec requires the html tag to have either the or amp attribute, that is, either <html ⚡> or <html amp> . It also requires <style amp-boilerplate> inside head . Should be easy to use JavaScript to check.

For the spec statements, see https://www.ampproject.org/docs/fundamentals/spec#required-markup

If you are using chrome browser then install below extension:

AMP Validator( https://chrome.google.com/webstore/detail/amp-validator/nmoffdblmcmgeicmolmhobpoocbbmknc?hl=en )

If current page is using AMP then this extension become active in browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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