Search code examples
jquerygoogle-chromegoogle-chrome-extension

How to inject jQuery using Chrome Extention with Manifest V3


I need to run some jQuery code from Content Script but some website doesn't include jQuery, is there any way to inject it? I tried this but it seem doesn't work at all

var script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js';
document.getElementsByTagName('head')[0].appendChild(script);

Solution

  • yes.

    If you want to access jquery before body then instead of "document_end" use "document_start" in manifest.json file.

    Answer 1.

    include it before your content script in manifest.json.

    1. download jquery version that you want to use.
    2. specify it in manifest.json

    manifest.json

    {
      "manifest_version": 3,
      "background": {
        "service_worker": "background.js"
      },
      "content_scripts": [
        {
          "matches": ["<tab_url_pattern>"],
          "run_at": "document_end", 
          "js": ["jquery3.5.1.min.js", "contentScript.js"],
          "all_frames": false
        },
      ]
    }

    Answer 2.

    expose jquery file using "Web_accessible_resource" and inject it in required tab using document.body.appendChild()

    {
      "manifest_version":3,
      "permissions": ["tabs"],
      "content_scripts":[{
          "matches": ["<url_pattern_1>"],
          "run_at": "document_end",
          "js": ["contentScript.js"],
          "all_frames": false
        }],
        "web_accessible_resources": [
        {
          "resources": ["jquery-1.11.3.min.js", "otherJquery.js"],
          "matches": ["<url_pattern_1>"]
        }
      ]
    }

    in contentScript.js

    const contentScriptLinks = ['jquery-1.11.3.min.js', 'otherJquery.js'];
    
    contentScriptLinks.forEach(src => {
      let el = document.createElement('script');
      el.src = chrome.runtime.getURL(src);
      document.body.appendChild(el);
    });