Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger Chrome extension on new tab open

I need to run Chrome extension when new tab is opened and html document is loaded.

Extension needs to check for new tab title and if it's equal to predefined string, tab should close.

For now, I have manage to write extension that works when I click on it's icon. But I want to make it to run without click on icon after the page is loaded in new tab.

Here is the current code.

function getCurrentTabData(callback) {
  var queryInfo = {
    active: true,
    currentWindow: true
  };
  chrome.tabs.query(queryInfo, function(tabs) {
    var tab = tabs[0];
    var title = tab.title;
    var id = tab.id;
    callback(title, id);
  });
}

document.addEventListener('DOMContentLoaded', function() {

  getCurrentTabData(function(title, id) {

    if(title == 'Page title') {
        chrome.tabs.remove(id, function() { });
    }

  });
});

And here is my manifest.json

{
  "manifest_version": 2,

  "name": "Auto close tab",
  "description": "Auto closes tab if title is matched",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png"
  },
  "permissions": [
    "activeTab"
  ]
}

How to make it run without click on it's icon?

like image 221
DusanSt Avatar asked Mar 15 '15 22:03

DusanSt


1 Answers

To accomplish this first of all you will need to have a Background Page that will manage your extension state. You can read about it here: https://developer.chrome.com/extensions/background_pages

Then in the background page script you will need to listen when the tab is created with this piece of code:

chrome.tabs.onCreated.addListener(function callback)

Here is documentation for this: https://developer.chrome.com/extensions/tabs#event-onCreated

Hope this will help to solve your issue.

like image 95
Rise Ledger Avatar answered Sep 24 '22 01:09

Rise Ledger