1

I'm trying to create a bookmarklet to display some of the objects in the dataLayer and I'm trying to display this data in a separate window.

This:

for (var i = 0; i < dataLayer.length; i++){ console.log(dataLayer[i]); }

can easily display the dataLayer at the console in a raw fashion but that's not what I want.

Can anyone help?

Thank you for your time.

Leustad
  • 143
  • 3
  • 13

1 Answers1

0

Create a data-display page that can accept MessageEvents containing the data you want to display:

<html>
  <head>
    <script>
      window.addEventListener("message", function(event) {

        /* for security, check event.origin here and
           return if not a safe/recognized URL */

        console.log(event.data); // prints message as string

        /* dynamically display data on page here */

      }, false);
    </scrip>
  </head>
  <body>

    <!-- put HTML template for display of data here -->

  </body>
</html>

Then in your bookmarklet, open the data-display page in a new window and send it the data using postMessage:

<!-- bookmarking this link creates the bookmarklet -->
<a href='javascript:(function() {
    var dataWin = window.open("dataDisplayPageUrl.html", "dataWin");
    dataWin.postMessage(dataLayer, "https://mywebsite.com");
})();'>bookmark this</a>

EDIT: Apparently more complicated in IE: Is cross-origin postMessage broken in IE10?

EDIT 2: Testing this in Chrome, it appears that there is a small delay between when a new window is opened and when it can receive messages. Adding a delay to the bookmarklet fixes the problem:

<!-- bookmarking this link creates the bookmarklet -->
<a href='javascript:(function() {
    var dataWin = window.open("dataDisplayPageUrl.html", "dataWin");
    window.setTimeout(function() {
        dataWin.postMessage(dataLayer, "https://mywebsite.com");
    }, 1000);
})();'>bookmark this</a>
Community
  • 1
  • 1
radiaph
  • 4,001
  • 1
  • 16
  • 19
  • I guess I should have explained better. Scenario: - User visits a page, - Clicks on the Bookmark - It opens a new window(which will be smaller) and displays all the data from dataLayer. – Leustad Mar 24 '15 at 17:53
  • Yes, that's what this code does. If you want the new window to be smaller, you can pass options to window.open. See docs here: https://developer.mozilla.org/en-US/docs/Web/API/Window/open – radiaph Mar 24 '15 at 18:54