What is the method for an iframe to retrieve the background color of its parent?

Currently, I am facing an issue with a Pardot (Salesforce) form that is displayed within an iframe. The problem arises when the form's transparent background clashes with the parent page's background color or photo, making it difficult to read the text on the form labels. For example, if the text for "First Name" is dark on a dark background, it becomes illegible.

To address this issue, my objective is to dynamically set a body class within the iframe based on the background color of the parent element where the frame is located. This will allow the iframe to determine whether the background is light or dark and adjust the text color accordingly.

In the provided code snippet, the iframe should be able to detect whether the div.framed-lead-form has a light or dark background. While there are JavaScript plugins available to extract color information from elements (such as this one with an intriguing license: https://gist.github.com/larryfox/1636338), I haven't come across any solution that works seamlessly across iframes.

<div class="framed-lead-form">
    <iframe src="//go.pardot.com/id" allowtransparency="true"></iframe>
</div>

Answer №1

Created a demonstration with the main document and an iframe.
The main document sends a theme using window.postMessage
The iframe listens for the message and changes the background color based on the theme.

Main document: https://jsfiddle.net/kristapsv/L1fd64b3/33/

(function($){

$.fn.lightOrDark = function(){
var r,b,g,hsp
  , a = this.css('background-color');

if (a.match(/^rgb/)) {
  a = a.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/);
  r = a[1];
  b = a[2];
  g = a[3];
} else {
  a = +("0x" + a.slice(1).replace( // thanks to jed : http://gist.github.com/983661
      a.length < 5 && /./g, '$&$&'
    )
  );
  r = a >> 16;
  b = a >> 8 & 255;
  g = a & 255;
}
hsp = Math.sqrt( // HSP equation from http://alienryderflex.com/hsp.html
  0.299 * (r * r) +
  0.587 * (g * g) +
  0.114 * (b * b)
);
if (hsp>127.5) {
  return 'light';
} else {
  return 'dark';
}
}

})(jQuery);

var iframe = document.getElementById('my-iframe');

// Determine light/dark theme based on container or other color
var theme =  $('.container').lightOrDark();

var jsonMessage = {
  'action' : 'set-theme',
  'theme' : theme
};

iframe.contentWindow.postMessage(JSON.stringify(jsonMessage), '*');

Iframe: https://jsfiddle.net/kristapsv/zLL9db1c/11/

var messageHandler = function (event) {
  var message;

  try {
    message = JSON.parse(event.data);
  } catch (e) {
    return;
  }

  switch (message.action) {
    case 'set-theme':
        setTheme(message.theme);
        break;
  }
};

var setTheme = function(theme) {
  $('.text-container')
    .removeClass('dark')
    .removeClass('light')
    .addClass(theme);
}

window.addEventListener('message', messageHandler, false);

Answer №2

As recommended by @charlietfl, one approach to consider is using the postMessage API to send a specific message to the iframed HTML document and then utilizing JavaScript to modify the background accordingly.

Answer №3

If you want to customize the background color of an iframe, you can easily do so by passing it as a parameter in the src attribute.

<div class="custom-iframe">
    <iframe src="//example.com?id=123&color=FFA500"></iframe>
</div>

To dynamically set the background color using JavaScript, you can retrieve the color value from the parent document and update the src attribute accordingly on DOM load. Here's a jQuery example:

$(function() {
    var customColor = getCustomColor();
    $('#my-frame').attr('src', '//example.com?id=123&color=' + customColor);
});

Answer №4

I have not personally verified this, but it is expected to retrieve the background color from within the iframe.

window.parent.document.getElementById('framed-lead-form').style.backgroundColor

Answer №5

Hopefully this will be effective

window.top.document.getElementsByTagName("body")[0].style.backgroundColor;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Build interactive web pages using Python scripts

By utilizing the Python scripts provided below, you can generate an HTML file with pre-set global variables (a, b, c, d). However, there might be instances when certain variables are not set globally, resulting in errors like "global 'a' is not d ...

The justify-content property aligns single-line text horizontally, but its alignment may not be consistent when the text expands over

Seeking a deeper understanding of flexbox alignment, I decided to experiment with aligning content using only flexbox properties. One puzzling observation is how "justify-content" centers items with single lines of text (flex-item-1 and flex-item-5), but n ...

What type does a React stateless functional component Flow return?

If I have a structure like this const RandomComponent = (props) => ( <div> <SomeSubComponent id={props.id} /> <AnotherSubComponent type={props.type} /> </div> ) How do I specify the return type using Flow, i.e., wha ...

Leverage AJAX on the client-side for optimal performance while utilizing node.js

I am currently working on a simple nodejs application that displays HTML pages. Within this application, there are two buttons that are linked to JavaScript functions in separate files. One of the functions uses ajax, while the other does not. However, I a ...

What could be causing the 304 error when using $http.get?

I'm a newcomer to angular and facing an issue with a service that was functioning perfectly, but suddenly stopped. The service I am referring to has the following method. this.retrieveForms = function() { return $http.fetch("/forms"). then(fu ...

Using Middleware to Access LocaleStorage in Universal Mode

Here's the dilemma: My understanding is that accessing LocaleStorage from Middleware in Universal mode is currently not possible (at least not out-of-the-box.) Question: Is there any way to solve this issue? Are there any modules or solutio ...

Text that disappears upon clicking on show/hide按钮

Could someone please help me figure out how to prevent the "See more" text from disappearing when clicked in the example below? I want it to stay visible. Thank you! ...

Divide a nested list into individual lists

I am working on a navigation menu with nested lists and I need to split the nested lists using jQuery while keeping the original headings intact. Can anyone help me achieve this? Below is the HTML code: <ul id="bigList"> <li><a href="#"& ...

Troubleshooting issues with Firebase integration in a Node.js environment

I am currently encountering difficulties implementing Firebase in my Node.js project. Below is the code snippet that I am attempting to execute on Node. var firebase = require("firebase"); var admin = require("firebase-admin"); var serviceAccount = requi ...

Is there a way to prevent the Pace js plugin from running on page load, but still have it execute during Ajax requests only?

I have successfully implemented the jquery pace plugin with a progress bar theme. Everything is working well, but I am looking to make it run only on ajax requests. I have tried various solutions found through research, but haven't had any luck. Belo ...

Center an image vertically in an AdminLte content-wrapper division

I am currently utilizing an AdminLte template as the framework for my design. In the designated area where I need to insert the main content, it is structured in the following manner: <div class="content-wrapper"> <se ...

Selecting the first li element using JQuery selectors

Can anyone help me with creating an onclick event that triggers when the user clicks on the first list item which is labeled as "Any Date"? I am looking to use jQuery to target this specific element. <ul id="ui-id-1" class="ui-menu ui-widget ui-widge ...

Selenium is having trouble finding the iframe element

I'm struggling to locate the input element within an iframe using Selenium. Even after trying switchTo().frame(id) and switchTo().frame(index), I am still unable to find it. This is the code snippet I have been using: driver.switchTo().defaultConten ...

Performing an Ajax MySQL query utilizing the text from a link as a reference, across a page

I have a page with several links. When a user clicks on a link, the text from the link is used in the WHERE clause of a MySQL query, and the result is displayed on the page using ajax. I'm trying to run different queries based on multiple ids or clas ...

What is the process for integrating require.js and jquery.min.js?

I am facing an issue with a specific piece of code: <script data-main="http://northapp.co/_a/js/main.min.js" src="http://northapp.co/_a/js/require.js"></script> Why am I unable to connect require.js with jquery.min.js? I have tried the follow ...

Using the highcharts-ng library in combination with ng-repeat was successful in creating multiple charts. However, in order to display different data for each chart, the

I need to provide the date either from the view template or possibly from the controller in order for the highchart to display the data specified by the <highchart /> directive. Explanation : <ul> <li ng-repeat="li in list"> ...

My goal is to exclusively create illustrations of items within a camera's view

Currently, I am using THREEJS to create a dynamically generated 'minecraft' world utilizing a perlin noise generator. Check out the progress so far: Block World Everything is going smoothly except that I am facing significant performance issues ...

Only scroll the div if it is not within the visible window

I've been looking at this snippet: The sidebar division is what I'm focusing on right now. I want the div to scroll along as I scroll down the page, but I need it to stop scrolling when its bottom is in view. The same should apply when scrollin ...

Problem with accessing state in React 16

In my code snippet below, I am encountering an issue. When the button is clicked and 'streaming' appears on the UI, the console.log within the 'process' function displays false. Can you help me identify what might be causing this discre ...

Cannot access console.log within Angular UI Router .config()=> {}

I've been working on connecting different parts of a basic Angular application, but I'm facing an issue where my initial view state is not loading. A major problem seems to be that I am unable to log inside the .config set up (even though I have ...