我正在玩建筑镀铬扩展。我在点击工具栏中的图标时正在测试popup.html功能。
然而,我很难用jquery结合chrome的异步方法来解决问题。* apis。也许有人可以为我进一步详细说明?
方案
popup.html包含与当前选项卡交互的按钮。按钮的href是根据当前选项卡的url +数组中的其他文本生成的。使用jQuery,我有一个$(“按钮”)。click();文档内部已准备就绪。然而这两个似乎并不好玩。除了jQuery之外的所有东西都可以。
例如
var the_current_url = '';
var url_addition = {
"button 1" : "/home",
"button 2" : "/about",
"button 3" : "/content"
}
function getCurrentURL(currentURL) {
if(currentURL) {
var scheme = currentURL.match(/^https?:\/\//i);
var newURL = '';
currentURL = currentURL.substring( scheme[0].length, currentURL.length );
currentURL = currentURL.substring( 0, currentURL.indexOf("/") );
the_current_url = newURL.concat(scheme[0], currentURL);
}
return true;
}
function buildButtons() {
var new_code = "<ul>\n";
// Generate the <li>
for (var key in url_addition) {
new_code = new_code.concat("<li><a href=\"",
the_current_url.concat(url_addition[key]),
"\" title=\"",
url_addition[key],
"\">",
key,
"</a></li>\n");
}
new_code = new_code.concat("</ul>");
return new_code;
}
// Get the Current URL and build the new url
chrome.tabs.query({
'active': true
}, function(tab) {
var currentURL = tab[0].url;
// Pass the Current URL to bb_current_url via Function
getCurrentURL(currentURL);
// add the popup buttons
document.getElementById("button-container").innerHTML = buildButtons();
});
$(document).ready(function() {
// Clicked on buttons
$("a").parents("#button-container").click(function() {
console.log("test" );
});
});
我能够获取当前标签的url并使用正确的链接构建按钮,但是当涉及到jquery点击操作时,它不起作用。似乎jquery的东西发生在按钮容器的按钮创建之前。这样$(“a”)的点击不会向console.log返回任何输出。任何人都知道我在这个例子中如何正确使用chrome的api和jquery?
答案 0 :(得分:1)
这与jQuery无关 - 普通JS也会出现同样的问题 基本上,您需要确保:
仅当准备就绪时,链接才会插入DOM (因此您的按钮容器已存在)。
行为附加到之后>>已插入DOM中。
您可以更改代码,以便在$(document).ready(...)
内插入链接(以确保按钮容器已经存在),并在插入链接后立即注册事件处理程序(以确保链接存在于DOM中。)
E.g:
/* Original comments omitted for brevity */
$(document).ready(function () {
/* The DOM is ready, so `#button-container` is guaranteed to be present */
chrome.tabs.query({ active: true } , function (tabs) {
var currentURL = tabs[0].url;
getCurrentURL(currentURL);
$('#button-container').html(buildButtons());
/* Place this inside the callback to ensure the links are present */
$('a').parents('#button-container').click(function() {
console.log('test');
});
});
});
顺便说一句,您的$('a').parents('#button-container')
将解析为#button-container
(不到孩子a
)。如果我没有弄错的话,您希望定位a
内的所有#button-container
而不是#button-container
本身。{
要实现这一点,请将表达式更改为:
$('#button-container a').click(function () {...});