Chrome extension: How to open a link in new tab?

JavascriptHtmlGoogle ChromeGoogle Chrome-ExtensionTabs

Javascript Problem Overview


In my Stackoverflow folder, I have stackoverflow.ico and 2 bellow files. When importing it to Chrome, it shows the icon in address bar, but when I click on it, Chrome doesn't open any new tab. What am I doing wrong?

manifest.json

{
  "name": "Stackoverflow",
  "version": "1",
  "browser_action":
  {
    "default_icon": "stackoverflow.ico"
  },
  "background":
  {
    "page": "index.html"
  },
  "permissions": ["tabs"],
  "manifest_version": 2
}

index.html

<html>
  <head>
    <script>
      chrome.browserAction.onClicked.addListener(function(activeTab)
      {
        var newURL = "http://stackoverflow.com/";
        chrome.tabs.create({ url: newURL });
      });
    </script>
  </head>
</html>

Javascript Solutions


Solution 1 - Javascript

The problem is that you are violating manifest version 2's content security policy. To fix it all you have to do is get rid of inline script, in this case your background page. Turn it into a background script like this:

manifest.json

"background":{
  "scripts": ["background.js"]
},

background.js

chrome.browserAction.onClicked.addListener(function(activeTab){
  var newURL = "http://stackoverflow.com/";
  chrome.tabs.create({ url: newURL });
});

If, for some reason, you do need it to be a page, then simply include the script as an external file and declare it as a page like before.

Solution 2 - Javascript

In my case I needed to open link in a new tab when I clicked a link within extension popup window, it worked fine with target attribute set to _blank:

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

Solution 3 - Javascript

I would prefer simpler solution - just add action to onclick

$('body').on('click', 'a[target="_blank"]', function(e){
    e.preventDefault();
    chrome.tabs.create({url: $(this).prop('href'), active: false});
    return false;
});

This will open all links (even links that were dynamically created) that have target="_blank" attribute in a new tab without loosing popup focus.

Solution 4 - Javascript

You do not need jQuery. Just use window.open("http://example.com", "_blank").

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThanh NguyenView Question on Stackoverflow
Solution 1 - JavascriptBeardFistView Answer on Stackoverflow
Solution 2 - JavascriptegoView Answer on Stackoverflow
Solution 3 - JavascriptfvrabView Answer on Stackoverflow
Solution 4 - JavascriptJaxonView Answer on Stackoverflow