How can I include short HTML code when new tab created or updated? **RESOLVED!**

I write little addon and point is in creating little block all thime when tab created or updated. I want to controll position of this block in browser popup.
So I created background script and included this function for connecting with content script:

// background.js:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    function createOverlay() {
        chrome.tabs.executeScript(null, {
            file: "/content_scripts/content-script.js"
        });
        chrome.runtime.sendMessage({message: 'Add block'});
    }

    chrome.tabs.onCreated.addListener(createOverlay);
    chrome.tabs.onUpdated.addListener(createOverlay);
});

…and nothing in content script:

// content-script.js:

function createOverlayElem(request, sender, sendResponse) {
    console.log(request);
}

chrome.runtime.onMessage.addListener(createOverlayElem);

But I can’t get any messages in content script while my popup was not opened… So I can’t get access to DOM tree of current tab where I want include my HTML.

Help please who know how can I always paste the same HTML code for all created or updated browser tabs?

I write little addon and point is in creating little block all thime when tab created or updated.

You want to insert an HTML element into every page? If so, then all you need is a "content_script" defined in the manifest.json. You don’t need to do anything in the background script for that.

I want to controll position of this block in browser popup.

You want to be able to move that element in the current tab / in all tabs with controlls that you have in the popup of the "browser_action"? If so, then your popup needs to send messages to that / those tabs.
Something like:

// on button click (or whatever)
chrome.tabs.query({ active: true, currentWindow: true, }, function([ tab, ]) {
    chrome.tabs.sendMessage(tab.id, { name: 'move', x: 42, y: -23, });
});

And within the content script:

const moveBy = (current, by) => current.replace(/^(-?\d+)px$|.*/, (_, px) => ((+px || 0) + by) +'px');

chrome.runtime.onMessage.addListener(message => {
    swich (message.name) {
        case 'move': {
            element.style.left = moveBy(element.style.left, message.x);
            element.style.top  = moveBy(element.style.top,  message.y);
        }
    }
});
1 Like
  • this variant doesn’t work. My code:

      // manifest.json
      {
          "manifest_version": 2,
          "name": "Addonnn",
          "version": "1.01",
          "description": "description",
          "icons": {
              "48": "icons/icon.png"
          },
          "permissions": [
              "activeTab",
              "storage"
          ],
          "browser_action": {
              "default_icon": "icons/icon.png",
              "default_title": "Title",
              "default_popup": "popup/popup.html"
          },
         "content_scripts": [
              {
                  "matches": ["<all_urls>"],
                  "js": ["jquery-1.12.3.min.js", "jqueryui.js", "content-script.js"],
                  "run_at": "document_start"     // I tried without this option
              }
          ],
          "background": {
              "scripts": ["background_scripts/background.js"]
          }
      }
    
      // content-script.js
      alert('Content script inited');
      console.log('Content script inited');
      var body = document.querySelector('body');
      body.style.backgroundColor = 'purple';
      function createOverlay() {
          alert('Updated or created');
          console.log('Updated or created');
          var body = document.querySelector('body');
          body.style.backgroundColor = 'red';
      }
      chrome.tabs.onCreated.addListener(createOverlay);
      chrome.tabs.onUpdated.addListener(createOverlay);
    
  • no one alert doesn’t work as expected. I tried to reinitialize addon, refresh web page, clean cache…

Hmm, I’d say at least the first alert() should work (the code after that not).

If you upload the code somewhere (e.g. on GitHub) I can try to run and fix it myself.

This is my GitHub repository:
Add-on-test
Thank a lot, NilkasG!

Chrome gives you a nice error message (and I think Firefox at least logs this too):

You have to include "js": ["content_scripts/content-script.js"],.

Also, if you "run_at": "document_start", document.body won’t exit yet.
You can ether use document.documentElement (the <html> tag) or run later.