0

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.

Community
  • 1
  • 1
bodacydo
  • 75,521
  • 93
  • 229
  • 319

3 Answers3

2

In your popup.js

$(document).ready(function(){
   $('body').on('click', 'a', function(){
     chrome.tabs.create({url: $(this).attr('href')});
     return false;
   });
});
Siddharth
  • 6,966
  • 2
  • 19
  • 34
1

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>
0

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.

bodacydo
  • 75,521
  • 93
  • 229
  • 319
  • Your code will always open this url not the one in href – Siddharth Jul 29 '15 at 09:35
  • Thanks @sid - you're right. But this also works if I know url in href already. – bodacydo Jul 29 '15 at 09:38
  • BTW, this happens because `chrome.browserAction.onClicked` [will not fire if the browser action has a popup](https://developer.chrome.com/extensions/browserAction#event-onClicked). – Teepeemm Jul 29 '15 at 14:40