Nick
Nick

Reputation: 2551

Chrome Extension - Append HTML & Run jQuery Function on Extension Click

So I'm in the midst of creating my first Chrome Extension (Trying)

I feel like I'm close... But I genuinely don't know what to google to get the answers I need. So I'm sorry if this is a silly question.

Essentially what I'm trying to do is on click of extension - Append HTML & CSS to body and run a jQuery function. But from the looks of it, I need to call in jQuery in the manifest? Which I think I've done and it's still not working.

My Code:

manifest.json

{
  "name": "Title",
  "description": "Description",
  "version": "1.0",
  "browser_action": {
      "default_title": "Hover Title",
      "default_icon": "icon.png"
  },
 "content_scripts": [ {
    "js": [ "jquery-1.7.2.min.js", "background.js" ],
    "matches": [ "http://*/*", "https://*/*"]
  }],
  "manifest_version": 2
}

background.js

chrome.browserAction.onClicked.addListener(function(tab) {

    (function ($) {
        $('body').append("Hello");
        alert("Hello");
        console.log("Hello");
    }(jQuery));

});

Any insight into where I'm going wrong would be massively helpful!

Thank you!!

Upvotes: 0

Views: 974

Answers (1)

woxxom
woxxom

Reputation: 73566

Chrome extension architecture is simple but it doesn't mean one can write code without studying it.

There are two methods of injecting content scripts:

  1. Unconditionally on all specified urls, in which case "content_script" key is used in the manifest and the content scripts communicate with the background page via runtime.sendMessage.
  2. Only when some event occurs like e.g. the user clicks our toolbar icon, in which case we only need the permission to access the active tab.

So in the given case we'll attach the icon click handler and inject the code afterwards:

  • manifest.json:

    {
        "name": "Title",
        "description": "Description",
        "version": "1.0",
        "browser_action": {
            "default_title": "Icon Title",
            "default_icon": "icon.png"
        },
        "background": {
            "scripts": ["background.js"]
        },
        "permissions": ["activeTab"],
        "manifest_version": 2
    }
    
  • background.js (this is an event page because we didn't use "persistent": true in the manifest, so be advised that the [global] variables will be lost after a few seconds of inactivity; instead you should use chrome.storage API or HTML5 localStorage/sessionStorage/and so on):

    chrome.browserAction.onClicked.addListener(function(tab) {
        chrome.tabs.executeScript({file: "jquery-1.7.2.min.js"}, function(result) {
            chrome.tabs.executeScript({file: "content.js"}, function(result) {
            });
        });
    });
    
  • content.js (the code runs in a sandbox so there's no need to hide global variables using IIFE)

    $('body').append("Hello");
    alert("Hello");
    console.log("Hello");
    

Upvotes: 1

Related Questions