简体   繁体   English

如何从内容脚本调用chrome.tabs.create API?

[英]How to call chrome.tabs.create API from content script?

I am developing a chrome extension where I want to inject a button on a web page. 我正在开发一个chrome扩展程序,该程序中我想在网页上注入一个按钮。 On clicking the button I want to call chrome.tabs.create API to open an HTML page into new tab. 点击该按钮后,我要调用chrome.tabs.create API,以将HTML页面打开到新标签页中。

As we know we can't directly open the tab using the content script, so what is the solution for implementing the above functionality. 众所周知,我们无法使用内容脚本直接打开选项卡,那么实现上述功能的解决方案是什么。

Lets say I am having an element name "button" injected on the button i have added the evnetHandler using following code but how to use this function to create the new tab in background.js 可以说我在按钮上注入了元素名称“ button”,我使用以下代码添加了evnetHandler,但是如何使用此功能在background.js中创建新标签

button.addEventListener('click',clickhandeler,true);

manifest.json file:- manifest.json文件:-

{
  "name": "my chrome extension",
  "version": "1.0",
  "manifest_version": 2,
  "description": "open the tab when button is cllicked",

  "permissions":["activeTab","tabs"],
    "background": {
    "scripts": ["event.js"],
    "persistent": false
},

  "browser_action": {
    "name": "Manipulate DOM",


    "default_icon": "icon.png"
  },
  "content_scripts": [ {
    "js": [ "jquery.min.js", "inject.js" ],
    "css": [ "inject.css" ],
    "matches": [ "http://*/*", "https://*/*"]
  }]
}

Following from comment: Why don't you send a message to your background script and have it open the new tab? 注释后:为什么不将消息发送到后台脚本并打开新选项卡?

In your page script: 在页面脚本中:

$('button').click(function(){
     chrome.runtime.sendMessage("newtab");
});

In your background.js 在您的background.js中

chrome.runtime.onMessage.addListener(function(message){
  if (message == "newTab){
     var url = "http://google.com/";
     chrome.tabs.create({ url: url });
  }
});

Note: this is a very simple example for this answer as you do not show your HTML. 注意:这是此答案的非常简单的示例,因为您没有显示HTML。 button will just match any button so you need to update that selector to match your HTML. button将只匹配任何按钮,因此您需要更新该选择器以匹配您的HTML。 Also, we typically have a payload structure used for messages, containing a message type (string) and other parameters. 同样,我们通常有一个用于消息的有效负载结构,其中包含消息类型(字符串)和其他参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM