How to add a class to the body tag inside an Iframe

Hi there, I'm working on an old website that uses an embedded iframe, and I'd like to add some styling to it. The issue is that I have to add a class to the body tag that is nested inside the iframe tag but that part is not available in the frontend code. So what I did was to add the "hiring-room" class to the iframe, and then try to target the body with css like this: .hiring-room html body { my styling etc } but that doesn't work. How would you access this highlighted line? whether it is with DOM manipulation or any other way
6 Replies
Jochem
Jochem2y ago
https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/contentWindow Though I think it only works if the origin is the same for the main page and the iframe page
HTMLIFrameElement.contentWindow - Web APIs | MDN
The contentWindow property returns the Window object of an HTMLIFrameElement. You can use this Window object to access the iframe's document and its internal DOM. This attribute is read-only, but its properties can be manipulated like the global Window object.
Muhct
Muhct2y ago
I followed that example and the styling I added (background color change) appears for half a second and then disappears... So I tried to add a class to the body inside the iframe like this:
const x = document.querySelector("iframe").contentWindow;
const xBody = x.document.querySelector("body").classList.add('myclass')
const x = document.querySelector("iframe").contentWindow;
const xBody = x.document.querySelector("body").classList.add('myclass')
but I don't see the class added when I inspect element on the website. Am I doing it correctly?
Jochem
Jochem2y ago
never really used it myself, but I did see online that it doesn't work cross origin, so unless you're embedding an iframe on the same domain, or who's cross origin policy you control, you might be SoL that looks fine though it's a pretty big security issue to be able to load a different page inside an iframe and manipulate it using javascript, so that's probably why it's locked off
MarkBoots
MarkBoots2y ago
I don't know what exactly is the thing what you want to load/style. But i see there is an /api/ in the url. Don't you have access to the data in json format? Then you can do with it what ever your like
Muhct
Muhct2y ago
I do have access to the json data but the embed I have right now also includes some styling, inputs, filters, etc - If I could add a class to the body tag highlighted it would be much simpler, but I wasn't able to do it with the code I shared two messages above
Coder_Carl
Coder_Carl2y ago
a really hacky work around would be to make a GET call to the address, and just grab all of the code / required bits and then pop that into a frame of your own you can make changes such as adding a className at that time
Want results from more Discord servers?
Add your server