Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery not working in chrome extension popup

I'm building my first chrome extension, and I'm having some trouble. I want to use jQuery on popup.html. The popup otherwise works fine, but the jQuery doesn't work.

Edit: I changed it, here's the new code, which still doesn't work. Any ideas? I've spent over two hours trying to figure it out. I'm a beginner to extensions and quite rusty in javascript and jquery, so it could definitely be something small and embarrassing... Thanks so much!

manifest.json

  "content_scripts": [{
    "matches": [website], 
    "js": [
    "content.js", 
    "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"]
   }], 

popup.html

<!DOCTYPE html>
<html>
<head>
    <title>First Google Extension</title>
    <style>
    body { 
        font-family: "Segoe UI"; 
        width: 300px; 
        font-size: 14px; 
        }; 

    #changeMe {
        color: blue; 
        font-style: bold; 
        }; 
    </style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>

<body>
    Welcome to my first Google Chrome Extension! <br> 
    <div id="changeMe">
        I'm different!
    </div>
</body>

</html>

popup.js

$(document).ready(function() {
        $("#changeMe").append("Test!");  
});
like image 592
microslayer Avatar asked Oct 11 '15 19:10

microslayer


2 Answers

You need to:

  1. Learn to debug extension popups. It will show you an informative error.

  2. Said error will refer to Content Security Policy. So you need to read about extensions' CSP.

  3. After you read the above documentation, the first problem you need to fix is trying to use a remote script. This is possible, but for something like jQuery it's best to download a copy of it, add it to extension's folder and include it as a local file:

    <!-- refers to extension's own folder -->
    <script src="jquery.min.js"></script>
    
  4. Second, you need to collect your own scripts inside a file and include it like that as well; inline code is not allowed in any form, and content scripts do not apply for extension pages.

like image 151
Xan Avatar answered Sep 20 '22 14:09

Xan


Also make sure to include jQuery.min.js before popup.js. I made this silly mistake, was loading popup.js before jQuery.min.js and it doesn't work that way. So always load jQuery.min.js first.

like image 42
nilesh Avatar answered Sep 19 '22 14:09

nilesh