2014-05-08 47 views
1

我想要制作一个Chrome扩展程序,其中我已经有一个带有多个锚点的HTML文件,并且正在尝试使Chrome单击时打开一个包含该URL的新标签。Chrome扩展程序导航到网址

为此,我在我的"permissions": ["tabs"]manifest.json

chrome.browserAction.onClicked.addListener(function(tab) { 
    chrome.tabs.create({'url': event.target.href}) 
}) 
在我的JS文件

;但那只是不起作用。我可能会错过什么?

问候, MTO

+0

对不起,我还是一个新的试图了解f ormatting :) –

+0

请使用搜索功能。 2天前提出了相同的问题。 – nietonfir

+0

我不明白...您如何期待浏览器操作图标知道您在浏览器操作图标“之前一段时间”点击的HTML元素的href? – devnull69

回答

1

这是怎么了,我通常做(例如:点击链接在popup.html)

popup.html

<a href="http://whereever.you.go.com/whatever.html" class="clickme">Click</a> 

弹出。 js

$('.clickme').click(function() { 
    chrome.tabs.create({url: $(this).attr('href')}); 
}); 

或香草的Javascript(与clickme类的每一个元素是一个锚)

window.addEventListener('load', function() { 
    var theAnchors = document.getElementsByClassName('clickme'); 
    for(i=0, len=theAnchors.length; i<len; i++) { 
     theAnchors[i].addEventListener('click', function() { 
     chrome.tabs.create({url: this.href}); 
     }, false); 
    } 
}, false); 
+0

当我有几个URL时,我不认为这会起作用。 –

+0

这真的很有趣。我有以下的HTML和JS,当我点击它时,URL似乎什么都不做。 Purchasing document.getElementByClassName('url')[0] .onclick = function(){ chrome.tabs.create({'url':event.target.href}); }; –

+0

event.target未定义。 'event'只在Internet Explorer中定义为全局对象,在Chrome中,您必须提供事件对象作为事件处理函数的参数'onclick = function(e){... e.target ...} ' – devnull69

0

最后我能做到这一点。

我所需要的代码是:

document.addEventListener('DOMContentLoaded', function() { 
    window.addEventListener('click', function(e) { 
    chrome.tabs.create({'url': event.target.href}); 
    }); 
}); 

非常感谢那些谁,甚至试图帮助:)

问候, K.

+0

如果点击发生,例如在''元素上会发生什么? – Xan

+0

这是个很好的问题@Xan,你有什么建议吗?也许将每个URL包装在一个单独的div中? –

+0

我会说 - 使用jQuery,'$('a')。click(function(e){/*...*/});'绑定到所有链接(只有链接)在同一时间。 – Xan

0

使用jQuery,我暗示重写在评论到另一个答案:

// Wait for the DOM to be ready, jQuery-style: 
$(document).ready(function() { 
    // Bind a click handler to all <a> elements: 
    $('a').click(function(e) { 
    // Event is passed into the handler as parameter "e" 
    chrome.tabs.create({'url': e.target.href}); 
    }); 
});