Chrome 扩展: 如何在新标签页打开链接?

在我的 Stackoverflow 文件夹中,我有 stackoverflow.ico和2个以下文件。当导入到 Chrome 时,它会在地址栏中显示图标,但是当我点击它时,Chrome 不会打开任何新标签。我做错了什么?

宣言 Json

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

Html

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

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.

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>

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.

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