在新标签上打开Chrome扩展程序 [英] Trigger Chrome extension on new tab open

查看:134
本文介绍了在新标签上打开Chrome扩展程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在打开新标签并加载HTML文档时运行Chrome扩展程序。

扩展需要检查新的标签标题,如果它等于预定义的字符串,则标签应该关闭。


现在,我已经设法在我点击它的图标时编写扩展程序。但是我想在页面加载到新选项卡后,不用点击图标就可以运行它。



这是当前的代码。

  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);
});

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

getCurrentTabData(function(title,id){

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

});
});

这里是我的manifest.json



<$
manifest_version:2,

name:自动关闭标签,
description:自动关闭标题匹配的标签,
version:1.0,

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

}

如何在没有点击图标的情况下运行它?

解决方案

需要有一个后台页面来管理你的扩展状态。你可以在这里阅读: https://developer.chrome.com/extensions/background_pages



然后在后台页面脚本中,您需要听取何时使用这段代码创建标签:

  chrome.tabs.onCreated.addListener(函数回调)

以下是此文档: https://developer.chrome.com/extensions/tabs#event -onCreated



希望这有助于解决您的问题。


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.

这篇关于在新标签上打开Chrome扩展程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆