diigo_为Diigo创建Chrome扩展程序,第3部分

diigo

In part 1, we introduced some new concepts and built a skeleton version of our extension, ready for installation and testing. Part 2 then took us through some helper methods and error handling, as well as parsing the result we got from Diigo and filtering out unique tags.

第1部分中 ,我们介绍了一些新概念,并构建了扩展的框架版本,可以进行安装和测试。 然后, 第2部分介绍了一些辅助方法和错误处理,并分析了从Diigo中获得的结果并过滤出了唯一的标记。

In Part 3 of this series, we'll write the body of our extension using everything we've done so far.

在本系列的第3部分中,我们将使用到目前为止所做的一切来编写扩展的主体。

制备 (Preparation)

I cleaned up the background.js file we made in the previous parts so go ahead and grab its content from Github. It's essentially identical, just reformatted and restructured slightly.

我清理了之前部分中制作的background.js文件,因此继续并从Github中获取其内容。 它本质上是相同的,只是重新格式化并稍微进行了重组。

书签事件的侦听器 (Listeners for bookmark events)

The first thing we'll do is add some listeners for bookmark events. Specifically, when a bookmark creation, change or deletion occurs, we want Diigo to know about it.

我们要做的第一件事是为书签事件添加一些侦听器。 具体来说,当书签创建,更改或删除发生时,我们希望Diigo知道它。

chrome.bookmarks.onCreated.addListener(function (id, node) {
    chrome.bookmarks.get(node.parentId, function (parent) {
        if (parent !== false) {
            chrome.bookmarks.get(parent[0].parentId, function (grandparent) {
                /** @namespace grandparent.title */
                if (grandparent[0] !== false && grandparent[0].title == "Tags") {
                    // Bookmark was created in proper location, send to Diigo
                    doRequest(node, parent[0].title);
                }
            });
        }
    });
});

chrome.bookmarks.onRemoved.addListener(function (id, removeInfo) {
    // To be added when API supports it
});

chrome.bookmarks.onChanged.addListener(function (id, changeInfo) {
    // To be added when API supports it
});

The bottom two listeners are just placeholders, because Diigo doesn't support this functionality yet. I'm told their API is soon to be upgraded, though, so we're putting them there nonetheless.

底部的两个侦听器只是占位符,因为Diigo尚不支持此功能。 我听说他们的API即将升级,因此我们还是把它们放在那里。

The onCreated listener first checks if the created bookmark node has a parent. If it does, then it checks the name of that parent's parent – and if that name is "Tags" we know we've got the right folder and we need to submit to Diigo. Now, this function assumes you have no other double-parent bookmark with "Tags" as the grandparent but, theoretically, it could happen. To check against that, we would need to add yet another parent level check for the Diigo master folder, but I'll leave that up to you for homework.

onCreated侦听器首先检查所创建的书签节点是否具有父节点。 如果是的话,它将检查该父母的父母的名字-如果该名字是“ Tags”,我们知道我们有正确的文件夹,我们需要提交给Diigo。 现在,此功能假定您没有其他以“标签”为祖父母的双亲书签,但从理论上讲,这可能会发生。 为了对此进行检查,我们需要为Diigo主文件夹添加另一个父级检查,但我将留给您进行家庭作业。

We then call doRequest with two parameters: the actual bookmark node that was created, and the name of the tag folder it was created in. Obviously, we need this data to tell Diigo which bookmark to create and which tag to give it. But why doRequest? Isn't that our "GET" function? Yep – but as you'll see in a moment, we'll modify it so that it can handle both the POST and GET action of our extension.

然后,我们使用两个参数调用doRequest :创建的实际书签节点以及在其中创建的标签文件夹的名称。显然,我们需要此数据来告诉Diigo创建哪个书签以及提供哪个标签。 但是为什么doRequest ? 这不是我们的“ GET”功能吗? 是的-但您很快就会看到,我们将对其进行修改,以便它可以处理我们扩展程序的POST和GET操作。

What we need to do next is add these params to our doRequest function, and have it react to their presence or absence, like so:

接下来,我们需要将这些参数添加到我们的doRequest函数中,并使它们对它们的存在或不存在做出React,如下所示:

var doRequest = function (bookmarknode, tag) {
    var xml = new XMLHttpRequest();

    if (bookmarknode !== undefined) {
        if (tag === undefined) {
            console.error("Tag not passed in. Unaware of where to store bookmark in Diigo. Nothing done.");
        } else {
            // Bookmark node was passed in. We're doing a POST for update, create or delete
            // Currently only create is supported
            var uriPart = encodeURI("url=" + bookmarknode.url + "&title=" + bookmarknode.title + "&tags=" + tag);
            xml.open('POST', rootUrl + uriPart);

            xml.setRequestHeader('Authorization', auth);
            xml.send();

            xml.onreadystatechange = function () {
                if (xml.readyState === 4) {
                    if (xml.status === 200) {
                        clog("Successfully created new bookmark in Diigo");
                    } else {
                        if (possibleErrors

!== undefined) { console.error(xml.status + ' ' + possibleErrors

); } else { console.error(possibleErrors.other); } } } }; }

} else {

xml.open('GET', rootUrl + "&count=100&filter=all&user="+user); xml.setRequestHeader('Authorization', auth); xml.send();

xml.onreadystatechange = function () { if (xml.readyState === 4) { if (xml.status === 200) { process(JSON.parse(xml.responseText)); } else { if (possibleErrors

!== undefined) { console.error(xml.status + ' ' + possibleErrors

); } else { console.error(possibleErrors.other); console.error(xml.status); } } } }; } };

If the bookmarknode and tag params are provided and valid, we execute the XHR request almost the same way as we did the original one for GETting the bookmarks, with one crucial difference – this time, we make it a POST request and add the title, tag, and bookmark name into the URL. That's all that's needed – now Diigo can accept our POST request and react accordingly. This is the beauty of RESTful API design.

Root bookmarks

Now let's save all the BBS-root bookmarks. We already have them in an array from the initial looping in the process function, but we don't do anything with them. Let's change that.

In Part 2, we made sure the "Diigo #BBS" folder exists. Once we're certain that it does, we can initiate the creation of the root bookmarks – they have a home we can put them in at that point.

Rewrite the part of the process function from this:

to

var folderName = 'Diigo #BBS';
        chrome.bookmarks.getFirstChildByTitle("1", folderName, function(value) {
            if (value === false) {
                chrome.bookmarks.create({
                    parentId: "1",
                    title: folderName
                }, function (folder) {
                    clog(folderName + " not found and has been created at ID " + folder.id);
                    processTagsFolder(folder, allTags);
                });
            } else {
                processTagsFolder(value, allTags);
            }
        });

As you can see, we added a new call to a processTagsFolder function. This function gets the "Diigo #BBS" folder passed in as the first parameter, and the array of all tags as the second. Seeing as this method executes either way – whether the "Diigo #BBS" folder pre-existed or not, we can put our root-bookmark-creation logic inside it.

In short, what we do here is fetch all the current root bookmarks, see if they're among the freshly downloaded ones and delete them if they're not (that means they've been untagged as bbs-root in Diigo), and finally, we add all the others. If you try it out, this should work wonderfully.

We also need to create the Tags folder if it doesn't exist. Add the following code right under the last bit:

chrome.bookmarks.getFirstChildByTitle(rootNode.id, 'Tags', function (tagsFolder) {
                    if (tagsFolder === false) {
                        chrome.bookmarks.create({
                            parentId: rootNode.id,
                            title: "Tags"
                        }, function (folder) {
                            processTags(folder, tagsArray);
                        });
                    } else {
                        processTags(tagsFolder, tagsArray);
                    }
                });

Obviously, we've made another function that gets called regardless of whether or not the Tags folder pre-existed. Let's define processTags.

Processing Tags

var doRequest = function (bookmarknode, tag) {
    var xml = new XMLHttpRequest();

    if (bookmarknode !== undefined) {
        if (tag === undefined) {
            console.error("Tag not passed in. Unaware of where to store bookmark in Diigo. Nothing done.");
        } else {
            // Bookmark node was passed in. We're doing a POST for update, create or delete
            // Currently only create is supported
            var uriPart = encodeURI("url=" + bookmarknode.url + "&title=" + bookmarknode.title + "&tags=" + tag);
            xml.open('POST', rootUrl + uriPart);

            xml.setRequestHeader('Authorization', auth);
            xml.send();

            xml.onreadystatechange = function () {
                if (xml.readyState === 4) {
                    if (xml.status === 200) {
                        clog("Successfully created new bookmark in Diigo");
                    } else {
                        if (possibleErrors

!== undefined) { console.error(xml.status + ' ' + possibleErrors

); } else { console.error(possibleErrors.other); } } } }; }

} else {

xml.open('GET', rootUrl + "&count=100&filter=all&user="+user); xml.setRequestHeader('Authorization', auth); xml.send();

xml.onreadystatechange = function () { if (xml.readyState === 4) { if (xml.status === 200) { process(JSON.parse(xml.responseText)); } else { if (possibleErrors

!== undefined) { console.error(xml.status + ' ' + possibleErrors

); } else { console.error(possibleErrors.other); console.error(xml.status); } } } }; } };

If the bookmarknode and tag params are provided and valid, we execute the XHR request almost the same way as we did the original one for GETting the bookmarks, with one crucial difference – this time, we make it a POST request and add the title, tag, and bookmark name into the URL. That's all that's needed – now Diigo can accept our POST request and react accordingly. This is the beauty of RESTful API design.

Root bookmarks

Now let's save all the BBS-root bookmarks. We already have them in an array from the initial looping in the process function, but we don't do anything with them. Let's change that.

In Part 2, we made sure the "Diigo #BBS" folder exists. Once we're certain that it does, we can initiate the creation of the root bookmarks – they have a home we can put them in at that point.

Rewrite the part of the process function from this:

to

var folderName = 'Diigo #BBS';
        chrome.bookmarks.getFirstChildByTitle("1", folderName, function(value) {
            if (value === false) {
                chrome.bookmarks.create({
                    parentId: "1",
                    title: folderName
                }, function (folder) {
                    clog(folderName + " not found and has been created at ID " + folder.id);
                    processTagsFolder(folder, allTags);
                });
            } else {
                processTagsFolder(value, allTags);
            }
        });

As you can see, we added a new call to a processTagsFolder function. This function gets the "Diigo #BBS" folder passed in as the first parameter, and the array of all tags as the second. Seeing as this method executes either way – whether the "Diigo #BBS" folder pre-existed or not, we can put our root-bookmark-creation logic inside it.

In short, what we do here is fetch all the current root bookmarks, see if they're among the freshly downloaded ones and delete them if they're not (that means they've been untagged as bbs-root in Diigo), and finally, we add all the others. If you try it out, this should work wonderfully.

We also need to create the Tags folder if it doesn't exist. Add the following code right under the last bit:

chrome.bookmarks.getFirstChildByTitle(rootNode.id, 'Tags', function (tagsFolder) {
                    if (tagsFolder === false) {
                        chrome.bookmarks.create({
                            parentId: rootNode.id,
                            title: "Tags"
                        }, function (folder) {
                            processTags(folder, tagsArray);
                        });
                    } else {
                        processTags(tagsFolder, tagsArray);
                    }
                });

Obviously, we've made another function that gets called regardless of whether or not the Tags folder pre-existed. Let's define processTags .

Processing Tags

翻译自: https://www.sitepoint.com/creating-chrome-extension-diigo-part-3/

diigo

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值