How to make a Content Script communicate with an iFrame element in extension for Chrome?

3

I developed a toolbar for Google Chrome by adding it to the pages through an iFrame:

var iframe = document.createElement('iframe');
iframe.id="iframeId";
iframe.src = chrome.extension.getURL('CLAWS_Sem_Imagens.html');
iframe.style.height = 7em;
iframe.style.width = '100%';
iframe.style.position = 'fixed';
iframe.style.top = '0';
iframe.style.left = '0';
iframe.style.zIndex = '938089'; 
//other stuff

document.documentElement.insertBefore(iframe,document.body); 

// pulling down the rest of the page
var bodyStyle = document.body.style;
var cssTransform = 'transform' in bodyStyle ? 'transform' : 'webkitTransform';
bodyStyle[cssTransform] = 'translateY(' + height + ')';

What I need is that when the user selects a word on the main page, it is stored in a variable (or HTML element) within that iFrame (logic already implemented). I therefore need the content-script and toolbar to communicate (the first recognizes that the word has been selected and stores it in a variable / element of the second).

For testing purposes, I'm trying to make the content-script recognize the existence of a span within the iframe:

  <span id="palavra">
  Palavra       
  </span>

I've tried to use iframe.contentDocument.getElementById("palavra") , window.document.getElementById("iframeId").contentWindow.querySelector("#palavra") and window.frames['iframeId'].contentDocument.getElementById('palavra') , but nothing works. Any suggestions?

    
asked by anonymous 15.09.2015 / 01:36

1 answer

2

From your question, you need to pick up the text selection event anywhere on the screen, and save that value to a variable within its extension. If this is really the code below solves your problem, if not explain the situation in the comments I reformulate the answer: D

For chrome extension it would look something like this:

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.sendRequest(tab.id, {method: "getSelection"}, function(response){
     setarConteudoSelecionado(response.data);
  });
});

function setarConteudoSelecionado(selectedText) {
  //seta conteudo na sua variavel :D
}

In pure JavaScript the idea would be this:

//declaro variavel para guardar seu texto
var textoSelecionado = '';

/*pega todos eventos de click, lembrando que 
o evento de click ele é trigado quando o botão é solto.
*/
document.body.addEventListener('click', pegarTexto, true);

/*metodo chamado pela função de click*/
function pegarTexto() {

    /*busca todos os texto selecionados na tela*/
    var selecionado = window.getSelection().toString();

    /*verifica se o evento é de seleção*/
    if (selecionado) {
        /*seta na sua variavel que deve estar na sua extensão*/
        textoSelecionado = selecionado;
        document.getElementById('ultimoTexto').innerHTML = selecionado;
    }
}

Follow the jsfiddle .

    
15.09.2015 / 02:54