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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With