Skip to content

Instantly share code, notes, and snippets.

@barna2019
Created July 20, 2020 10:44
Show Gist options
  • Save barna2019/91b1ed281170ed10bd964539ea0035f7 to your computer and use it in GitHub Desktop.
Save barna2019/91b1ed281170ed10bd964539ea0035f7 to your computer and use it in GitHub Desktop.
amp-web-push-helper-frame.html
<!doctype html>
<html>
<!-- AMP Web Push Helper IFrame -->
<head>
<meta charset="utf-8">
<script>(function(){var f;function g(a){for(var b=["object"==typeof globalThis&&globalThis,a,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof global&&global],c=0;c<b.length;++c){var d=b[c];if(d&&d.Math==Math)return d}return function(){throw Error("Cannot find global object");}()}var h=g(this);function k(a,b){b=void 0===b?"":b;try{return decodeURIComponent(a)}catch(c){return b}};var l=/(?:^[#?]?|&)([^=&]+)(?:=([^&]*))?/g;var n=self.AMP_CONFIG||{},p=("string"==typeof n.cdnProxyRegex?new RegExp(n.cdnProxyRegex):n.cdnProxyRegex)||/^https:\/\/([a-zA-Z0-9_-]+\.)?cdn\.ampproject\.org$/;function r(a){if(self.document&&self.document.head&&(!self.location||!p.test(self.location.origin))){var b=self.document.head.querySelector('meta[name="'+a+'"]');b&&b.getAttribute("content")}}n.cdnUrl||r("runtime-host");n.geoApiUrl||r("amp-geo-api");self.__AMP_LOG=self.__AMP_LOG||{user:null,dev:null,userForEmbed:null};var t=self.__AMP_LOG;function v(){if(t.dev)return t.dev;throw Error("failed to call initLogConstructor");};/*
https://mths.be/cssescape v1.5.1 by @mathias | MIT license */
function w(){this.M=100;this.D=this.J=0;this.A=Object.create(null)}w.prototype.has=function(a){return!!this.A[a]};w.prototype.get=function(a){var b=this.A[a];if(b)return b.access=++this.D,b.payload};w.prototype.put=function(a,b){this.has(a)||this.J++;this.A[a]={payload:b,access:this.D};if(!(this.J<=this.M)){v().warn("lru-cache","Trimming LRU cache");a=this.A;var c=this.D+1,d;for(d in a){var e=a[d].access;if(e<c){c=e;var m=d}}void 0!==m&&(delete a[m],this.J--)}};(function(a){return a||{}})({c:!0,v:!0,a:!0,ad:!0,action:!0});var x,y;
function z(a){x||(x=self.document.createElement("a"),y=self.__AMP_URL_CACHE||(self.__AMP_URL_CACHE=new w));var b=y,c=x;if(b&&b.has(a))a=b.get(a);else{c.href=a;c.protocol||(c.href=c.href);var d={href:c.href,protocol:c.protocol,host:c.host,hostname:c.hostname,port:"0"==c.port?"":c.port,pathname:c.pathname,search:c.search,hash:c.hash,origin:null};"/"!==d.pathname[0]&&(d.pathname="/"+d.pathname);if("http:"==d.protocol&&80==d.port||"https:"==d.protocol&&443==d.port)d.port="",d.host=d.hostname;d.origin=
c.origin&&"null"!=c.origin?c.origin:"data:"!=d.protocol&&d.host?d.protocol+"//"+d.host:d.href;b&&b.put(a,d);a=d}return a};function A(a){a||(a={debug:!1,windowContext:window});this.w={};this.m={};this.l=a.debug;this.B=this.N=this.O=!1;this.C=this.H=this.I=this.j=this.G=null;this.h=a.windowContext||window}f=A.prototype;
f.listen=function(a){var b=this;return(new Promise(function(c,d){b.B?d(Error("Already connected.")):b.O?d(Error("Already listening for connections.")):Array.isArray(a)?(b.I=b.W.bind(b,a,c,d),b.h.addEventListener("message",b.I),b.l&&v().fine("amp-web-push","Listening for a connection message...")):d(Error("allowedOrigins should be a string array of allowed origins to accept messages from. Got:",a))})).then(function(){b.send(A.Topics.CONNECT_HANDSHAKE,null);b.B=!0})};
f.W=function(a,b,c,d){var e=d.data,m=d.origin,E=d.ports;this.l&&v().fine("amp-web-push","Window message for listen() connection received:",e);a:{var q=z(m).origin;for(var u=0;u<a.length;u++)if(z(a[u]).origin===q){q=!0;break a}q=!1}q?e&&e.topic===A.Topics.CONNECT_HANDSHAKE?(v().fine("amp-web-push","Received expected connection handshake message:",e),this.h.removeEventListener("message",this.I),this.j=E[0],this.C=this.K.bind(this),this.j.addEventListener("message",this.C,!1),this.j.start(),b()):v().fine("amp-web-push",
"Discarding connection message because it did not contain our expected handshake:",e):v().fine("amp-web-push","Discarding connection message from "+m+" because it isn't an allowed origin:",e," (allowed origins are)",a)};
f.connect=function(a,b){var c=this;return new Promise(function(d,e){a||e(Error("Provide a valid Window context to connect to."));b||e(Error("Provide an expected origin for the remote Window or provide the wildcard *."));c.B?e(Error("Already connected.")):c.N?e(Error("Already connecting.")):(c.G=new MessageChannel,c.j=c.G.port1,c.H=c.V.bind(c,c.j,b,d),c.j.addEventListener("message",c.H),c.j.start(),a.postMessage({topic:A.Topics.CONNECT_HANDSHAKE},"*"===b?"*":z(b).origin,[c.G.port2]),v().fine("amp-web-push",
"Opening channel to "+b+"..."))})};f.V=function(a,b,c){this.B=!0;this.l&&v().fine("amp-web-push","Messenger channel to "+b+" established.");a.removeEventListener("message",this.H);this.C=this.K.bind(this);a.addEventListener("message",this.C,!1);c()};
f.K=function(a){a=a.data;if(this.w[a.id]&&a.isReply){var b=this.w[a.id];delete this.w[a.id];var c=b.promiseResolver;b.message=a.data;this.l&&v().fine("amp-web-push","Received reply for topic '%s': %s",a.topic,a.data);c([a.data,this.L.bind(this,a.id,b.topic)])}else{var d=this.m[a.topic];if(d){this.l&&v().fine("amp-web-push","Received new message for topic '"+(a.topic+"': "+a.data));for(var e=0;e<d.length;e++)(0,d[e])(a.data,this.L.bind(this,a.id,a.topic))}}};
f.on=function(a,b){this.m[a]?this.m[a].push(b):this.m[a]=[b]};f.off=function(a,b){if(b){var c=this.m[a].indexOf(b);-1!==c&&this.m[a].splice(c,1)}else this.m[a]&&delete this.m[a]};f.L=function(a,b,c){var d=this,e={id:a,topic:b,data:c,isReply:!0};this.j.postMessage(e);return new Promise(function(a){d.w[e.id]={message:c,topic:b,promiseResolver:a}})};
f.send=function(a,b){var c=this,d={id:crypto.getRandomValues(new Uint8Array(10)).join(""),topic:a,data:b};this.l&&v().fine("amp-web-push","Sending %s: %s",a,b);this.j.postMessage(d);return new Promise(function(e){c.w[d.id]={message:b,topic:a,promiseResolver:e}})};
h.Object.defineProperties(A,{Topics:{configurable:!0,enumerable:!0,get:function(){return{CONNECT_HANDSHAKE:"topic-connect-handshake",NOTIFICATION_PERMISSION_STATE:"topic-notification-permission-state",SERVICE_WORKER_STATE:"topic-service-worker-state",SERVICE_WORKER_REGISTRATION:"topic-service-worker-registration",SERVICE_WORKER_QUERY:"topic-service-worker-query",STORAGE_GET:"topic-storage-get"}}}});function B(){var a={debug:!1};this.l=a&&a.debug;this.h=a.windowContext||window;this.o=new A({debug:this.l,windowContext:this.h});this.F={}}function C(a,b){a({success:!0,error:void 0,result:b})}f=B.prototype;f.P=function(a,b){if(a&&a.isQueryTopicSupported){var c=!1,d;for(d in A.Topics)a.isQueryTopicSupported===A.Topics[d]&&(c=!0);C(b,c)}else C(b,Notification.permission)};
f.U=function(a,b){var c=null;try{if(a&&a.key&&this.h.localStorage)c=this.h.localStorage.getItem(a.key);else{if(!t.user)throw Error("failed to call initLogConstructor");t.user.warn("amp-web-push","LocalStorage retrieval failed.")}}catch(d){}C(b,c)};
f.T=function(a,b){C(b,{isControllingFrame:!!this.h.navigator.serviceWorker.controller,url:this.h.navigator.serviceWorker.controller?this.h.navigator.serviceWorker.controller.scriptURL:null,state:this.h.navigator.serviceWorker.controller?this.h.navigator.serviceWorker.controller.state:null})};
f.S=function(a,b){if(!a||!a.workerUrl||!a.registrationOptions)throw Error("Expected arguments workerUrl and registrationOptions in message, got:",a);this.h.navigator.serviceWorker.register(a.workerUrl,a.registrationOptions).then(function(){C(b,null)}).catch(function(a){C(b,a?a.message||a.toString():null)})};f.messageServiceWorker=function(a){this.h.navigator.serviceWorker.controller.postMessage({command:a.topic,payload:a.payload})};
f.R=function(a,b){var c=this;if(!a||!a.topic)throw Error("Expected argument topic in message, got:",a);(new Promise(function(b){c.F[a.topic]=b;c.waitUntilWorkerControlsPage().then(function(){c.messageServiceWorker(a)})})).then(function(d){delete c.F[a.topic];return C(b,d)})};
function D(a){a=a.h.location.search;var b=Object.create(null);if(a)for(var c;c=l.exec(a);){var d=k(c[1],c[1]);c=c[2]?k(c[2].replace(/\+/g," "),c[2]):"";b[d]=c}if(!b.parentOrigin)throw Error("Expecting parentOrigin URL query parameter.");return b.parentOrigin}f.X=function(a){a=a.data;var b=a.payload,c=this.F[a.command];"function"===typeof c&&c(b)};function F(a){return a.h.navigator.serviceWorker&&a.h.navigator.serviceWorker.controller&&"activated"===a.h.navigator.serviceWorker.controller.state}
f.waitUntilWorkerControlsPage=function(){var a=this;return new Promise(function(b){F(a)?b():a.h.navigator.serviceWorker.addEventListener("controllerchange",function(){F(a)?b():a.h.navigator.serviceWorker.controller.addEventListener("statechange",function(){F(a)&&b()})})})};
f.run=function(a){var b=this;this.o.on(A.Topics.NOTIFICATION_PERMISSION_STATE,this.P.bind(this));this.o.on(A.Topics.SERVICE_WORKER_STATE,this.T.bind(this));this.o.on(A.Topics.SERVICE_WORKER_REGISTRATION,this.S.bind(this));this.o.on(A.Topics.SERVICE_WORKER_QUERY,this.R.bind(this));this.o.on(A.Topics.STORAGE_GET,this.U.bind(this));this.waitUntilWorkerControlsPage().then(function(){b.h.navigator.serviceWorker.addEventListener("message",b.X.bind(b))});this.o.listen([a||D(this)])};
window._ampWebPushHelperFrame=new B;window._ampWebPushHelperFrame.run();})();
//# sourceMappingURL=amp-web-push-helper-frame.js.map
</script>
</head>
<body>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment