bodacydo
bodacydo

Reputation: 79539

How do I open a new tab with URL in Google Chrome Extension on click? (with code example that i've)

I'm trying to open a new tab in Google Chrome Extension. I've simplified my test case to this HTML:

<a id="link" href="http://www.example.com">example</a>

Here's code that I've:

$('#link').click(function () {
  chrome.browserAction.onClicked.addListener(function (activeTab) {
    var newURL = "http://www.youtube.com/watch?v=oHg5SJYRHA0";
    chrome.tabs.create({ url: newURL });
  });
});

I found the answer chrome.browserAction.onClicked.addListener in this thread:

Google Chrome Extensions - Open New Tab when clicking a toolbar icon

But this doesn't work when I click my link and I don't understand how to use chrome.browserAction.onClicked.addListener in my case.

Any help appreciated.

Upvotes: 0

Views: 2159

Answers (3)

Dmitry Artamoshkin
Dmitry Artamoshkin

Reputation: 116

You can just add attribute target="_blank" to the links in your popup.html.

<a id="link" href="http://www.example.com" target="_blank">example</a>

Upvotes: 1

bodacydo
bodacydo

Reputation: 79539

I found answer myself:

$('#link').click(function () {
  var newURL = "http://www.youtube.com/watch?v=oHg5SJYRHA0";
  chrome.tabs.create({ url: newURL });
});

No need for chrome.browserAction.onClicked.addListener.

Upvotes: 0

Siddharth
Siddharth

Reputation: 7166

In your popup.js

$(document).ready(function(){
   $('body').on('click', 'a', function(){
     chrome.tabs.create({url: $(this).attr('href')});
     return false;
   });
});

Upvotes: 2

Related Questions