- Javascript inject js to iframe code example
- Injecting Javascript to Iframe
- Is there a way to inject javascript code from an iframe into the parent window?
- Example:
- Inject script inside iframe of different domain
- Injecting Javascript in iframe using selenium
- How to inject code into an iframe
- Use it to pre-fill dynamic forms like adding a promo code to eventrbite embedded tickets
- Method 1: JavaScript
- Method 1b: Embedded Script Editing
- Method 2: HTML attributes
- inject a javascript function into an Iframe
Javascript inject js to iframe code example
For the script tag, I’m pretty sure you’ll have to create a new script tag and reinsert it, but there’s no way to get rid of older code that has already been parsed other than redefining global symbols. You can redefine global symbols with subsequent scripts, but not remove previous scripts or their effects.
Injecting Javascript to Iframe
These two lines of code look like they could have problems:
csstag = contents.find('head').append(' ').children('style'); java = contents.find('head').append('').children('script');//Issues here
It seems like it would be much better to create the style tag and remember that DOM element.
var iframe = document.getElementById("preview_content"); var iframewindow = iframe.contentWindow || iframe.contentDocument.defaultView; var doc = iframewindow.document; var csstag = doc.createElement("style"); var scripttag = doc.createElement("script"); var head = doc.getElementsByTagName("head")[0]; head.appendChild.cssTag; head.appendChild.scriptTag; $('.area_content_box').focus(function() < var $this = $(this); var check = this.id; $this.keyup(function() < if (check === "html_process") else if(check === "css_process") < // I don't know if you can just replace CSS text like this // or if you have to physically remove the previous style tag // and then insert a new one csstag.text($this.val()); >else if (check === "java_process") < // this is unlikely to work // you probably have to create and insert a new script tag each time java.text( $this.val() ); >>); >);
This should work for the body HTML and it may work for the CSS text into the style tag.
I do not believe it will work for the javascript as you can’t change a script by assigning text to the tag the way you are. Once a script has been parsed, it’s in the javascript namespace.
There is no public API I’m aware of for removing previously defined and interpreted scripts. You can redefine global symbols with subsequent scripts, but not remove previous scripts or their effects.
If this were my code, I’d remove the previous style tag, create a new one, set the text on it before it was inserted in the DOM and then insert it in the DOM.
If you’re not going to do it that way, then you’ll have to test to see if this concept of setting .text() on an already inserted (and parsed) style tag works or not in all relevant browsers.
For the script tag, I’m pretty sure you’ll have to create a new script tag and reinsert it, but there’s no way to get rid of older code that has already been parsed other than redefining global symbols. If you really wanted to start fresh on the code, you’d have to create a new iframe object from scratch.
There are other issues with this too. You’re installing a .keyup() event handler every time the .area_content_box gets focus which could easily end up with many of the event handlers installed, all getting called and all trying to do the same work.
Inject javascript into a javascript function, To turn this into a function, we need to make the code evaluate in global scope. Originally, this answer made use of with to change the scope of the eval, but this doesn’t currently work in browsers. Instead, .call is used to change the scope of eval to window. (function () < var begin = /^function\s*\w*\s*\ ( [^)]*\)\s* …
Is there a way to inject javascript code from an iframe into the parent window?
All you need to do is use the global parent variable in the iframe , either by using window.parent or parent directly.
Example:
So long as the iframe satisfy the Same-Origin Policy, this will work.
Yes, as long as they’re on the same domain. This has been asked before on stack overflow, see this thread.
In short (from linked thread)
document.getElementById('someDiv').innerHTML = top.document.getElementById('otherIframe').contentWindow. document.getElementById('someOtherDiv').innerHTML;
Html — Javascript Iframe Inject to beginning of tag, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more
Inject script inside iframe of different domain
Nope. Same Origin Policy dates back to Netscape 2.0.
Unless you can hack/XSS the other site’s files to inject the JS, you will have a hard time.
Now if you legitimately need to communicate with the other page, and you either have control of the other page or can setup it to communicate with your server, you can use window.postMessage , JSONP or even Ajax with CORS (latter 2 will be harder to pass dynamic content though). But I believe it is not the case.
Javascript inject html in iframe Code Example, const iframe = document.getElementById(«myIframe»); const iWindow = iframe.contentWindow; const iDocument = iWindow.document; // accessing the element const element
Injecting Javascript in iframe using selenium
To inject code into each iframe you first have to switch to it
import org.openqa.selenium.JavascriptExecutor; List elements = driver.findElements(By.tagName("iframe")); for(WebElement element:elements) < driver.switchTo().defaultContent(); driver.switchTo.frame(element); if (driver instanceof JavascriptExecutor) < ((JavascriptExecutor) driver).executeScript("alert('hello world');"); >System.out.println(element.getAttribute("id")); >
Use JavascriptExecutor for writing javascript code in selenium
JavascriptExecutor js = (JavascriptExecutor) driver; WebElement element = driver.findElement(By.linkText("Click ME")); js.executeScript("arguments[0].setAttribute('attr', '10')",element);
Best way to inject html using javascript, If performance is a concern, stay away from innerHTML. You should create the whole object tree using document.createElement() as many times as needed, including for nested elements.. Finally, append it to the document with one statement, not many statements.
How to inject code into an iframe

Use it to pre-fill dynamic forms like adding a promo code to eventrbite embedded tickets
Injecting code or prefilling fields in an iframe can be a tricky task, but with a little bit of know-how, it’s definitely doable. If you’re looking to add some extra functionality to your website, or if you just want to streamline the user experience, then this is the guide for you.
First, let’s define what an iframe is. An iframe (short for «inline frame») is an HTML element that allows you to embed one HTML document within another. Essentially, it’s a window within a window, and it’s a great way to add extra functionality to your website without cluttering up your main page.
Now, let’s talk about how to inject code or prefill fields in an iframe. There are a few different ways to do this, but we’ll focus on two of the most popular methods: JavaScript and HTML attributes.
Method 1: JavaScript
The first method is to use JavaScript to inject code into an iframe. This is a great option if you need to add some dynamic functionality to your iframe, such as a form validation script. To do this, you’ll need to use the contentWindow property of the iframe element to access the iframe’s document object. Once you have access to the document object, you can use the innerHTML property to add your code. Here’s an example:
iframe id="myiframe" src="https://example.com"> iframe> script> var iframe = document.getElementById("myiframe"); var doc = iframe.contentWindow.document; doc.innerHTML = "Hello, World!
"; script>
Method 1b: Embedded Script Editing
In some cases, you might have received a pre-compiled embed script code for an iframe from a service you want to add to your website, an Eventbrite ticket page.
In the latter case, this is what Eventbrite gives you:
div id="eventbrite-widget-container-YOUREVENTID"> div> script src="https://www.eventbrite.co.uk/static/widgets/eb_widgets.js"> script> script type="text/javascript"> var exampleCallback = function( ) < console.log('Order complete!'); >; window.EBWidgets.createWidget(< // Required widgetType: 'checkout', eventId: 'YOUREVENTID', iframeContainerId: 'eventbrite-widget-container-YOUREVENTID', // Optional iframeContainerHeight: 425, // Widget height in pixels. Defaults to a minimum of 425px if not provided onOrderComplete: exampleCallback // Method called when an order has successfully completed >); script>
As you can see the original service provider, like in the second option, may have a script available online that it runs from a url. In this case it also already modifies it locally, so we may take advantage of that second script to see if we can inject parameters directly in there.
You can copy and paste the script url in your browser to check the source code. In this case: https://www.eventbrite.co.uk/static/widgets/eb_widgets.js
Let’s say we wanted to prefill our embedded checkout with a promotional code. Even though the unformatted javascript code appears jibberish at first, we can search the text for words like «property» or even more specific ones, like «promo» or «promocode» to see if the script defines these form elements.

Since we identified the right parameter in the script generating the widget within the iframe, let’s go and try to add it directly into the suggested creation method:
script type="text/javascript"> var exampleCallback = function( ) < console.log('Order complete!'); >; window.EBWidgets.createWidget(< // Required widgetType: 'checkout', eventId: 'YOUREVENTID', promoCode: 'earlybird', iframeContainerId: 'eventbrite-widget-container-YOUREVENTID', // Optional iframeContainerHeight: 425, // Widget height in pixels. Defaults to a minimum of 425px if not provided onOrderComplete: exampleCallback // Method called when an order has successfully completed >); script>
Success! Now our eventbrite embedded checkout widget comes pre-filled with a promotional code of our choice.

Method 2: HTML attributes
The second method is to use HTML attributes to prefill fields in an iframe. This is a great option if you want to prefill fields in a form, such as a login form. To do this, you’ll need to use the name attribute of the input elements to identify the fields you want to prefill. Here’s an example:
iframe src="https://example.com/login"> form> label>Username: label> input type="text" name="username" value="JohnDoe"> label>Password: label> input type="password" name="password" value="password123"> input type="submit"> form> iframe>
It’s important to note that for the second method, it’s a bit different as you need to include the entire HTML code inside the iframe, it’s not only injecting code to the iframe but also creating it as well.
In conclusion, injecting code or prefilling fields in an iframe is definitely possible, and it’s a great way to add extra functionality to your website or streamline the user experience. Whether you choose to use JavaScript or HTML attributes, the process is fairly straightforward and can be done in just a few lines of code.
inject a javascript function into an Iframe
secondly you can manipulate dom and window objects of the frame directly through JS:
frames[0].window.foo = function()
to get your frame from a DOMElement object you can use:
var myFrame = document.getElementById('myFrame'); myFrame.contentWindow.foo = function()
Note that the scope in foo is NOT changed, so window is still the parent window etc. inside foo.
If you want to inject some code that needs to be run in the context of the other frame you could inject a script tag, or eval it:
frames[0].window.eval('function foo()< console.log("Im in a frame",window); >');
Though the general consensus is to never use eval, I think its a better alternative than DOM injection if you REALLY need to accomplish this.
So in your specific case you could do something like:
frames[0].window.eval(foo.toString());
Here’s my solution. I’m using jquery to insert the content, then using eval to execute the script tags in the context of that iframe:
var content = $($.parseHTML(source, document, true)); $("#content").contents().find("html").html(content); var cw = document.getElementById("content").contentWindow; [].forEach.call(cw.document.querySelectorAll("script"), function (el, idx) < cw.eval(el.textContent); >);
This code is the result of my research. The accepted answer also helped me a lot. First of all, I create a simple iframe:
For access to iframe’s window and document I used this code.
const iframe = document.getElementById('myiframe'); const iframeWin = iframe.contentWindow || iframe; const iframeDoc = iframe.contentDocument || iframeWin.document;
Finally I injected js codes into iframe:
var script = iframeDoc.createElement("script"); script.append(` window.onload = function() < document.getElementById("fire").addEventListener('click', function() < const text = document.getElementById('title').innerText; alert(text); >) > `); iframeDoc.documentElement.appendChild(script);