Editing Css on an iframe with React

I've got a wordpress site that is pulling in a script from a 3rd party app via a script that loads an iframe onto the page. Then, that iframe has a form with buttons.

Once one of the buttons is clicked, it erases those buttons from the page & writes in a new set of elements. The form has messed up CSS, so I'm looking to add a class to it such that it is sized properly, yet I can't get the following code to reliably work all the time. Running it in a console will work, but then setting it when page loads does not. How can I add a class to an element with the selector

'div.main-content.booking-user.col-md-8 > form'

Here's the code I'm trying ( note, pure Javascript as jQuery is not on the page )

document.querySelector('iframe').addEventListener('click', function(){
console.log('click captured');
var script = document.createElement("script");
script.innerHTML = "console.log('added CSS for form'); document.querySelector('div.main-content.booking-user.col-md-8 > form').className='col-md-8';";

1 answer

  • answered 2018-03-22 05:22 AnilRedshift

    If this works some of the time but not others, my suspicion is that the div.main-content.booking-user.col-md-8 > form element is not present at page load time. If that's the case (but it is present some short time afterwards, you could wrap your script code in a setTimeout or setInterval call to delay for some time.

    something like this:

    let intervalID;
    intervalId = setInterval(() => {
      const element = document.querySelector('div.main-content.booking-user.col-md-8 > form');
      if (element) {
        element.className = 'col-md-8';
        intervalID = null;
    }, 1000);

    Another possibility is that some other code is resetting or otherwise changing the iframe later.

    Lastly, because the div is in an iframe, is the origin the same? Otherwise you can't access the innards due to cross-site-scripting issues. However, since you've said this works some of the time I'm assuming that's not the case here.