Fearcustard Fearcustard - 2 months ago 5
HTML Question

Chrome Extension | Sending "this" and "this" id value using a Chrome API like message

Stackoverflow community, hello. I am here asking for some help with figuring out how to send

"this"
with
the id of "this"
using the message API for Google chrome extensions.

Relevant html code used (popup.html)

<p class="field switch bpos">
<label class="cb-enable" id="id1"><span>yes</span></label>
<label class="cb-disable selected"><span>no</span></label>
<input type="checkbox" id="checkbox" class="checkbox">
</p>


Listener.js (external script) (placed within script tags at the of popup.html)

$( ".cb-enable" ).click(function() {
chrome.tabs.executeScript(null, {file:"script.js"});
});


Script.js (run from {file:"script.js"} )

function check(){
if ( $( this ).is('#id1')) {function1(); }
else if ( $( this ).is('#id2')) {function2(); }
else{alert("id not found");}
}
check();


Being relatively new to the chrome extension APIs, the use of file and sending information from one script to the other using the messaging API has got me rather confused, and am hoping one of you could help me a bit with how exactly
"this"
with
the ID value of this
was sent from one file to the other.

If anyone could help even in the slightest of this specific request, your help would be incredibly appreciated.

Answer

First of all, you must take in mind, that DOM tree of popup.html and DOM tree accessible from your injected script.js are different. So on if you pass jQuery event to script.js, it would not work proper. Instead of it, you can pass target id to your script.js.

Secondly, why you inject your script.js to the page every click? You may do it once. And then send messages to the page.

Thirdly, you work with DOM in your Listener.js, which may be not ready, I recommend to bind it to document.ready:

It may be like:

Listener.js:

$(document).ready(function(){
    chrome.tabs.executeScript(null, {file:"script.js"});
    $( ".cb-enable" ).click(function(evt) {
        target=$(this).attr(id)
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            chrome.tabs.sendMessage(tabs[0].id, target, function(response) {
            });
        });
    });
});

script.js:

if(!window.init)
{
  window.init=true
  chrome.runtime.onMessage.addListener(function(msg){
    //do something with msg contains id of clicked button
  });
}

Fourly, you use jQuery in your script.js, are you injected it as content_script? If not, you need to do it by adding jquery to your plugin and injecting it as content_script in manifest:

  ...
  "content_scripts": [
    {
      "js": [
        "jquery.js"
      ],
      "matches": [
        "http://*/*","https://*/*"
      ]
    }
  ],
  ...
Comments