Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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> 
like image 817
Thanh Nguyen Avatar asked May 12 '13 03:05

Thanh Nguyen


People also ask

How do I get Chrome to open links in a new tab?

Right-clicking on a link and selecting "Open Link in New Tab" also opens the link in a new tab on Chrome, even without the Chrome Toolbox extension. In addition, you might be able to click the middle button or wheel on your mouse to open a link in a new tab, depending on your mouse settings.

Can you force a URL to open in a new tab?

You can make a HTML link open in a new tab by adding the target=”_blank” attribute. You should insert this after the link address.


2 Answers

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.

like image 78
BeardFist Avatar answered Oct 04 '22 16:10

BeardFist


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> 
like image 25
ego Avatar answered Oct 04 '22 17:10

ego