我正在查看bookmarks.create()的MDN Javascript API示例。我正在尝试实施他们必须学习如何创建文件夹的示例:
function onBookmarkAdded(bookmarkItem) {
console.log("Bookmark added with ID: " + bookmarkItem.id);
}
chrome.bookmarks.create({
title: "bookmarks.create() on MDN",
url: "https://developer.mozilla.org/Add-ons/WebExtensions/API/bookmarks/create"
}, onBookmarkAdded);
据我所知,这没有任何作用。任何有关如何为书签制作文件夹的帮助或其他示例都将非常感激。
答案 0 :(得分:2)
假设您已将"bookmaks"
添加到 manifest.json 文件中的permissions
,那么您的代码将按照书面形式工作以创建书签。由于您的 manifest.json 文件未包含在问题中,因此我们无法确定这是否是问题。
要创建书签文件夹,您可以省略url
属性,或在传递给bookmark.create()
的对象中提供url:null
以下是完整的,经过测试的(在FF48.0.2和Developer Edition上,FF50.0a2),扩展名。它包含在代码中,允许在单击browser_action
按钮时创建书签。我发现当单击browser_action
按钮而不是仅在安装/ Firefox运行时,测试更容易执行。它会:
bookmarks.create() on MDN
My Bookmark Folder A
My Bookmark Folder B
My Bookmark Folder B.1
My Bookmark Folder B
醇>
所有这些都是在"其他书签"因为在为这些扩展程序创建的书签文件夹的子项中的任何一个调用parentId
时没有提供bookmark.create()
。
background.js :
//* For testing, open the Browser Console
try{
//alert() is not supported in Firefox. This forces the Browser Console open.
// This abuse of a misfeature works in FF49.0b+, not in FF48
alert('Open the Browser Console.');
}catch(e){
//alert() throws an error in Firefox versions below 49
console.log('Alert() threw an error. Probably Firefox version below 49.');
}
//*
chrome.browserAction.onClicked.addListener(function(tab) {
doBrowserAction();
});
function doBrowserAction(){
console.log('Background: Doing action');
createABookmark();
createABookmarkFolder();
createABookmarkFolderWithinABookmarkFolder();
}
function onBookmarkAdded(bookmarkItem) {
console.log("Bookmark added with ID: " + bookmarkItem.id, bookmarkItem);
}
function createABookmark(){
chrome.bookmarks.create({
title: "bookmarks.create() on MDN",
url: "https://developer.mozilla.org/Add-ons/WebExtensions/API/bookmarks/create"
}, onBookmarkAdded);
}
function createABookmarkFolder(){
chrome.bookmarks.create({
title: "My Bookmark Folder A",
url: null
}, onBookmarkAdded);
}
function createABookmarkFolderWithinABookmarkFolder(){
chrome.bookmarks.create({
title: "My Bookmark Folder B",
url: null
}, bookmarkItem => {
onBookmarkAdded(bookmarkItem);
chrome.bookmarks.create({
title: "My Bookmark Folder B.1",
url: null,
parentId: bookmarkItem.id
},onBookmarkAdded
);
});
}
的manifest.json :
{
"description": "Create a bookmark on browser_action button click",
"manifest_version": 2,
"name": "Demo: Create Bookmark",
"version": "0.1",
"applications": {
"gecko": {
//Firefox: must define id to use some features (e.g. option_ui)
"id": "demo-create-bookmark@example.com",
"strict_min_version": "48.0"
}
},
"permissions": [
"bookmarks"
],
"background": {
"scripts": [
"background.js"
]
},
"browser_action": {
"default_icon": {
"32": "myIcon.png"
},
"default_title": "Do Action",
"browser_style": true
}
}
显然,如果你打算使用各种函数而不是演示,你会想要使它们更通用(即传递回调,书签属性等)。
注意:请参阅标题为"General notes on testing and development of WebExtensions in Firefox" of this answer的部分。你的陈述,"据我所知,这没有任何意义",暗示你没有看Browser Console的错误消息或控制台日志。