Search code examples
javascriptiframeembedselectorparent

Copy div from parent website to a textarea in iframe


In the Google Translator I've made a second instance of Google Translate with

var makediv = document.createElement("secondinstance");
makediv.innerHTML = '<iframe id="iframenaturalID" width="1500" height="300" src="https://translate.google.com"></iframe>';
makediv.setAttribute("id", "iframeID");
var getRef = document.getElementById("gt-c");
var parentDiv = getRef.parentNode;
parentDiv.insertBefore(makediv, getRef);

And I'm trying to copy text from auto-correction of the first instance to the textarea of the second instance: image

I'm trying this (this code works if I just copy html within the Chrome inspector{using [0] or [1] to select elements with the same IDs}, however it's only possible to use two instances of the translator with iframe embedding):

setInterval(function() {
    var childAnchors1 = window.parent.document.querySelectorAll("#spelling-correction > a");
    var TheiFrameInstance = document.getElementById("iframeID");
    TheiFrameInstance.contentWindow.document.querySelectorAll("#source").value = childAnchors1.textContent;
}, 100);

But the console says that it cannot read property "document" of undefined at eval, and says that the problem is in this line:

  TheiFrameInstance.contentWindow.document.querySelectorAll("#source").value = childAnchors1.textContent;

I've tried embedding another website, and it also didn't work. I also tried to call iframe by "iframenaturalID", and tried to write TheiFrameInstance.contentWindow.document.querySelectorAll without the contentWindow, but nothing seems to work. I would very much appreciate any help.


Solution

  • Ok, I made it work with a different method of creating iframe:

    var a = document.createElement('iframe');
    a.src = "https://translate.google.com"; 
    a.id = "iframenaturalID";
    a.width = "1000";
    a.height = "500";
    document.querySelector('body').appendChild(a)
    

    And (copying textcontent from the correction div to the iframe textarea):

    let iframe = document.getElementById("iframenaturalID");
    setInterval(function() {
    let source = iframe.contentWindow.document.getElementById("source");
    let destination = window.parent.document.querySelector("#spelling-correction > a");
    
    
    source.value = destination.textContent;
         }, 100);
    

    Now it does what I tried to do, however I still get mistake message: Uncaught TypeError: Cannot set property 'value' of null at eval, which points at this line: source.value = destination.textContent;. It's not a big problem though, but still it's strange that it returns this mistake...