0

I'm creating a simple chrome extension that basically detects if exists a script with the id of "x" is loaded in the page that the user is landed, if I call the id by jQuery works fine, but when i loaded in chrome extension popup.js it doesn't work, is there something wrong with my code?

Some landing page html:

 <script data-cfasync="false"  id="somename" type="text/javascript">...

Popup.js

document.addEventListener('DOMContentLoaded', function() {

  console.log($('#clevernt').length);

    if ($('#somename').length == 0) {
    $('#title').html('Script does not exists.<br> <span class="dot-red"></span>');
}else{
$('#title').html('Script exists.<br> <span class="dot-green"></span>');
}

}, false);

Manifest.json:

{
  "manifest_version": 2,

  "name": "name",
  "description": "This extension will check if clever script is loaded",
  "version": "1.0",

  "browser_action": {
   "default_icon": "icon.png",
   "default_popup": "popup.html"
  },
  "content_scripts":[
   {
     "matches":["<all_urls>"],
     "js":["jquery.js"]
   }  
  ],
  "permissions": [
   "activeTab"
   ]
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

0

The popup is a totally separate extension page with a URL like chrome-extension://id/popup.html. It's not related to web pages.

The content_scripts section automatically runs the listed scripts in web pages, not in the extension pages, so jquery.js declared in your manifest.json loads in web pages, but not in the popup because the popup is not a web page.

So, your popup script currently does not have jquery.js. You should see an error if you open the correct devtools: since the popup is a separate page in a separate window it has its own separate devtools. Right-click inside the popup, then click "inspect" to open the correct devtools where you will see the error messages.

Currently your popup.js looks for an element inside its own popup page, not in the web page.
To access DOM of a web page you need a content script.

  1. load jquery.js in popup.html: <script src=jquery.js></script>
  2. load popup.js in popup.html at the end before the closing </body> tag so you won't need DOMcontentLoaded or jQuery.ready() or $() wrapper: <script src=popup.js></script></body>
  3. remove content_scripts section from manifest.json
  4. use programmatic injection

popup.js:

chrome.tabs.executeScript({code: `(${inContent})()`}, ([result] = []) => {
  $('#title').html(
    chrome.runtime.lastError ? 'Error: ' + chrome.runtime.lastError.message :
      result ? 'Script exists.<br> <span class="dot-green"></span>' :
        'Script does not exist.<br> <span class="dot-red"></span>');
});

// this function will run as a content script code
// so it can't use jQuery because we don't inject it anymore for simplicity
function inContent() {
  // the returned value must be JSON-compatible
  // so we can't return a DOM element
  return !!document.getElementById('somename');
}
wOxxOm
  • 65,848
  • 11
  • 132
  • 136