Nelson Silva
Nelson Silva

Reputation: 439

Passing data to iframe to customize content

I have an iFrame which has a button inside and that button, on click, will expand the iframe to its content's height. Now, this button has to be customizable on its color, border-color and text-color. I thought about using the iFrame attributes to send the data I need, the colors in this case, but I see no way of doing so. A workaround that I'm trying is to set this info in the iframe's name and parse it, but it doesn't look like the best approach.

Upvotes: 0

Views: 63

Answers (1)

Alexis Wilke
Alexis Wilke

Reputation: 20725

The IFRAME name is definitely not a very good solution. You can instead use data attributes, at least.

There are, I'm sure many ways of doing such. If the colors change dynamically, it will be important to have a way to communicate. If not dynamic, you could also define them as query string parameters in the IFRAME URL and use those colors directly on your server to define the corresponding script including the colors from the get go (although that means your data changes depending on the colors...)

From a script using jQuery and defined in the IFRAME, you can access the IFRAME tag with window.frameElement. So, I would write something like this:

var f = window.frameElement;
if(f)
{
    var c, bc, tc;

    c = jQuery(f).data("color");
    bc = jQuery(f).data("border-color");
    tc = jQuery(f).data("text-color");
}

Now the c, bc, and tc variables have your colors.

Note that I test f to make sure it exists. If your current window is not defined inside an IFRAME, then f == null and you probably want to handle that special case in some way, be it ignoring it as in my exampl above.

The corresponding HTML looks like this:

<iframe id="my-iframe"
        data-color="#112233"
        data-border-color="#aabbcc"
        data-text-color="#666666"
        ...>
</iframe>

In case you want to access the IFRAME from the parent window, you can use its id attribute instead:

var iframe = jQuery("id");
c = iframe.data("color");
[...]

Upvotes: 1

Related Questions