Arun Thomas
Arun Thomas

Reputation: 845

Chrome extension to change DOM with a button in extension popup

i am completely new to chrome extension development. I am trying to change the DOM (append data to active webpage) when clicked on a button in the extension popup. How is this possible.

the manifest file

{
  "manifest_version": 2,

  "name": "test 2",
  "description": "test ext 2",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "content_scripts": [
    {
      "matches": ["http://*/*","https://*/*"],
      "js": ["jquery.min.js", "main.js"]
    }
  ],
  "permissions": [
   "activeTab"
   ]
}

suppose if the popup.html file is

<!doctype html>
<html>
  <head>
    <title>test extension 2</title>
    <script src="popup.js"></script>
  </head>
  <body>
    <a id="button">button</a>
  </body>
</html>

and when i click on #button, i want to execute some jquery code in main.js file which will append some data to the active webpage.

Thank you.

Upvotes: 6

Views: 7202

Answers (1)

Haibara Ai
Haibara Ai

Reputation: 10897

  1. Use Programmatic injection. You could register event listener in popup.js and call chrome.tabs.executeScript to inject some js code/file to current active tab. This requires host permissions.

    popup.js

    document.getElementById('button').addEventListener('click', function() {
        chrome.tabs.query({ active: true, currentWindow: true}, function(activeTabs) {
            // WAY 1
            chrome.tabs.executeScript(activeTabs[0].id, { code: 'YOUR CODE HERE' });
        });
    });
    
  2. Use Message Passing. You could call chrome.tabs.sendMessage in popup.js and listen to that via chrome.runtime.onMessage in content.js.

    popup.js

    // WAY 2 (Replace WAY1 with following line)
    chrome.tabs.sendMessage(activeTabs[0].id, { action: 'executeCode' });
    

    content.js

    chrome.runtime.onMessage.addListener(function(request) {
        if(request.action === 'executeCode') {
            // YOUR CODE HERE
        }
    });
    
  3. Use Storage. You could call chrome.storage.local.set in popup.js and listen to storage change in content.js via chrome.storage.onChanged.

    popup.js

    // WAY 3 (Replace WAY1 with following line)
    chrome.storage.local.set({ action: 'executeCode' });
    

    content.js

    chrome.storage.onChanged.addListener(function(changes) {
        var action = changes['action'];
        if(action.newValue === 'executeCode') {
            // YOUR CODE HERE
        }
    });
    

Upvotes: 15

Related Questions