nate
nate

Reputation: 139

Chrome Extension '$ is not defined'

I've copied the code from a tutorial and I think I might be missing a new addition. This is inside of my popup.js file which is linked correctly in my popup.html file. The goal here is to have a budget tracker that adds the input to the 'total' id.

Here is the code I am working with inside of popup.js

$(function() {
  $('#spendAmount').click(function() {
    chrome.storage.sync.get('total', function(budget) {
      var newTotal = 0;
      if (budget.total) {
        newTotal += parseInt(budget.total);
      }

      var amount = $('#amount').val();
      if (amount) {
        newTotal += parseInt(amount);
      }

      chrome.storage.sync.set({
        'total': newTotal
      });

      $('#total').text(newTotal);
      $('#amount').val('');

    });
  });
});
<!DOCTYPE html>
<html>

<head>
  <title>Budget Manager</title>
  <script type="text/javascript" src="popup.js"></script>
  <script type="text/javascript" src="jquery-3.4.1.min.js"></script>
</head>

<body>
  <h1>Budget Manager</h1>
  <h2>Total Spent: <span id="total">0</span></h2>
  <h2>Limit: <span id="limit"></span></h2>
  <h3>Enter Amount</h3>
  <input type="text" id="amount" />
  <input type="submit" id="spendAmount" value="Spend">
</body>

</html>

manifest.json

{
    "manifest_version": 2,
    "name": "Budget Manager",
    "version": "1.0",
    "description": "This extension tracks your overall spendings.",
    "icons": {
        "128": "icon128.png",
        "48": "icon48.png",
        "16": "icon16.png"
    },
    "browser_action": {
        "default_icon": "icon16.png",
        "default_popup": "popup.html"
    },

    "permissions": [
        "storage"
    ]
}

Upvotes: 0

Views: 98

Answers (2)

muellerra
muellerra

Reputation: 64

The reason for this is that the script calling for jQuery loads prior to jQuery.js loading.

  • fix = having the background script load jQuery itself

or

  • Try changing JQuery to its minimized version - in some cases it has shown success. Content scripts are reloaded automatically but changes to manifest.json only become effective after reloading your Chrome extension.

Upvotes: 0

Amit
Amit

Reputation: 4350

You are loading jQuery after your script. When your script is executed there is no jQuery, So $ is not defined at that time. Move popup below jQuery

    <script type="text/javascript" src="jquery-3.4.1.min.js"></script>
    <script type="text/javascript" src="popup.js"></script>

Upvotes: 2

Related Questions