I have a javascript based Google Chrome Extension that takes as input the currently selected text in the web page, and then translates that text into English. The original text is replaced with the translated text at same position...
I have a requirement where some sites will be shown in an iframe, and for those sites also I want to translate the currently selected text within the iframe.
The source code at the beginning of the extension, where it obtains the currently selected text, is given below--
var selection = document.getSelection();
var range = selection.getRangeAt(0);
How do I change the above code/add some code so that the variable 'selection' can store either the currently selected text in main window, or the currently selected text within an iframe? Also the variable 'range' should be initialised correctly even if the text to be translated is within an iframe...
Also, once the translation is done, the original language text is replaced by translated text at same place in web page, the variable 'replacement' stores the translated text--
var holder = document.createElement('span');
holder.innerHTML = replacement;
var child = holder.firstChild;
var ref = child.cloneNode(true);
// ... now insert into document in place of the original content:
range.deleteContents();
range.insertNode(ref);
while (child = child.nextSibling) {
ref.parentNode.insertBefore(child.cloneNode(true), ref.nextSibling);
ref = ref.nextSibling;
}
Note that the code for initialisation of 'range' is given in the first code section shown in this question...
How do I go about modifying the above code so that the new span element is created within the iframe? What I understood is that to do this, the key part is the code
var holder = document.createElement('span');
The variable 'holder' should be able to create the span element in an iframe also...
How do I modify this code?