2

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://*/*"]
  }]
}
3
  • Why don't you send a message to your background script and have it open the new tab? Commented Sep 1, 2015 at 11:35
  • can you please elaborate how to do that ? I have edited the question accordingly. Commented Sep 1, 2015 at 11:40
  • Why don't you just use a link? Commented Sep 1, 2015 at 20:32

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Close the "newTab" in your background.js example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.