skip to Main Content

Im working on webchat integration using 3rd party library and i want to customize the style. I want to append the style to head (inside the iframe), I have written the code like below, but it still won’t work.

enter image description here

Code

$('#qontak-webchat-widget').contents().find('head')
  .append(`<style type='text/css'> #qontak-webchat { background-color: red; } </style>`)

2

Answers


  1. Your jquery is targeting $('#qontak-webchat-widget').contents().find('head'). which is looking for a head element that is a child element of the #qontak-webchat-widget.

    As head is a child of html and a sibling of body, you wont be able to locate head as you are trying to do it.

    Try adjusting your jquery to:

    $('head').append(`<style type='text/css'> #qontak-webchat { background-color: red; } </style>`)
    

    If you need to modify the head located in an iframe, use the technique given in this answer to access the contents of the iframe.

    Login or Signup to reply.
  2.   // Wait for the document to be ready
    
      // Find the iframe element by its ID
      var iframe = $('#myFrame');
    
      // Access the iframe's head element
      var iframeHead = iframe.contents().find('head');
    
      // Create a new style element
      var styleElement = $('<style>')
        .attr('type', 'text/css')
        .text('body { background-color: yellow; }');
    
      // Append the style element to the iframe's head
      iframeHead.append(styleElement);
    });
    

    In the above example, we first wait for the document to be ready using $(document).ready() function.

    Then, we find the iframe element by its ID using $(‘#myFrame’).

    We access the iframe’s head element using contents().find(‘head’).

    Next, we create a new style element using $(”) and set its attributes and text content. Finally, we append the style element to the iframe’s head using append().

    Make sure the iframe source is from the same domain to avoid cross-origin issues.

    If you are using a 3rd party library to manipulate the contents of the and want to append a style to its head element, you’ll need to ensure that the library has provided a way to access and modify the contents of the iframe.

    Typically, if the library supports iframe manipulation, it should provide a method or API to access the iframe’s document or contents. Once you have access to the document, you can use regular JavaScript or jQuery to modify its contents.

    It may be blocked for access as well.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search