![]() Let me know in the comments if you have any other ideas as to how we might use postMessage in new and interesting ways. I could see how this feature might even lead to new and more powerful uses of iFrames, as tunnels or proxies to interact with sites on other domains. Hopefully, this new feature will provide a clear and safe method of interacting with iFrames. This results in a more seamless navigation experience where you can quickly switch between dashboards without reloading the page. The security, in place for good reasons, makes them somewhat of a black box to javascript. When embedding SharpTools.io dashboards within in an iframe, you can use the postMessage API on modern browsers to perform client-side navigation of your embedded SharpTools.io dashboards. Using iFrames has often been a frustrating experience. Now, the origin can send a message to the URL of the remote (matching the URL of the iFrame): iframe = document.getElementById('content') ('sizing?', '') įinally, the listener on the remote will respond to the message event it was set up to receive with respondToSizingMessage. respondToSizingMessage = function(e) window.addEventListener('message', handleSizingResponse, false) When the IFrame has loaded, we pass MessageChannel.port2 to the IFrame using window.postMessage along with a message. ![]() Both the origin and remote must listen for, and send, messages.įirst, let's set up our listener on the remote side, and later we'll handle the respondToSizingMessage. In the following code block, you can see a new channel being created using the MessageChannel() constructor. The origin is the site that has an iFrame and the remote will be the site loaded into the iFrame. ![]() I will refer to them as the origin and remote. Here's how we can use it to ask for the height and width of our iFrame document. Thankfully, as part of the draft HTML5 specification we get cross-document messaging thanks to the method postMessage. Domains, protocols and ports must match." This, of course, fails (on the first line) with an error message similar to: "Unsafe JavaScript attempt to access frame with URL from frame with URL file:///index.html. It might look something like this: iframeBody = document.getElementById('content'). iframeHeight = iframeBody.scrollHeight iframeWidth = iframeBody.scrollWidth In the course of experimenting with click tracking and heatmaps I needed to discern the size of the content on a page loaded within an iFrame in order to resize a canvas that I was overlaying.Ī first attempt way be to go right at the information as if it was contained within our own page. Here's how I used postMessage to get the height and width of a document in an iFrame. ![]() Javascript now allows cross-document communication thanks to the postMessage function. To javascript, iFrames are typically black boxes. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |