简体   繁体   中英

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. On clicking the button I want to call chrome.tabs.create API to open an HTML page into new tab.

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.addEventListener('click',clickhandeler,true);

manifest.json file:-

{
  "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

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. button will just match any button so you need to update that selector to match your HTML. Also, we typically have a payload structure used for messages, containing a message type (string) and other parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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