作为Chrome的重度使用者,解决了访问Google的问题之后,书签又经常不能同步。
利用Chrome的Api接口获取所有书签,然后上传到自己的服务器数据库保存。本来想使用七牛云的接口储存,但是七牛云只能上传文件保存。所以自己实现了一个简单的Flask框架Python后台来保存。
- 上传书签到服务器
- 从服务器拉取书签恢复(待实现)
179个书签上传成功
synced
主要逻辑:
chrome.bookmarks.getTree()
接口返回的书签数据是数组和树结合的,使用递归比较方便提取。
document.addEventListener('DOMContentLoaded', function() {
getBookmarks();
});
var bookmarks;
function getBookmarks(){
bookmarks = []
chrome.bookmarks.getTree(function(result){
for(var i=0;i<result.length;i++){
reversBookmarks(result[i]);
}
syncBook();
});
}
function reversBookmarks(result){
if(result==null){
return;
}
var bookmark = {
id:result.id == null ? 0 : result.id,
parentId:result.parentId == null ? 0 : result.parentId,
index:result.index == null ? 0 : result.index,
url:result.url == null ? 'None' : result.url,
title:result.title == null ? 'None' : result.title
}
bookmarks.push(bookmark)
if(result.children==null){
return;
}
for(var i=0; i<result.children.length;i++){
reversBookmarks(result.children[i]);
}
}
function syncBook(){
jsonStr = JSON.stringify({data:bookmarks});
$.ajax({
type: "post", url: "http://***/uploadBookmark", async: "true",
data: {
'key':new Date().toLocaleDateString(),
'data':jsonStr
}, success: function (data,status) {
console.log(data);
obj = JSON.parse(data);
code = obj.code;
count = obj.count;
error = obj.error;
$('#loading').hide();
if(code==0){
$('#sync').text('OK!Synced '+count+' bookmarks.');
}else{
$('#sync').text('Failed! Error:'+error+' Status:'+status);
$('#btnRetry').show();
}
}, error: function (error) {
$('#loading').hide();
$('#sync').text('Failed! Error:'+error);
$('#btnRetry').show();
}
});
}
后台实现:
@app.route('/uploadBookmark', methods=['POST'])
def uploadBookMark():
key = request.form.get('key')
data = request.form.get('data')
return dbBookmark.saveBookMark(key, data)
import json
import os
import sqlite3
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
DATABASE = os.path.join(PROJECT_ROOT, 'bookmark.chromeExtension')
def initDB():
conn = None
try:
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
cursor.execute(
'CREATE TABLE bookmark (id INT PRIMARY KEY , parentId INT, indexId INT,url VARCHAR (20),title VARCHAR(20))')
cursor.close()
conn.commit()
except BaseException as e:
print e
finally:
if conn:
conn.close()
def saveBookMark(key, data):
bookMarks = json.loads(data)
data = bookMarks.get('data')
conn = None
count = 0
error = 'null'
try:
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
sql = "DELETE FROM bookmark"
cursor.execute(sql)
for bookMark in data:
id = bookMark.get('id')
pId = bookMark.get('parentId')
iId = bookMark.get('index')
url = bookMark.get('url').encode('utf-8')
title = bookMark.get('title').encode('utf-8').replace("'", " ")
sql = "INSERT INTO bookmark (id,parentId,indexId,url,title) VALUES ('{}','{}','{}','{}','{}')" \
.format(id, pId, iId, url, title)
try:
cursor.execute(sql)
count = count + cursor.rowcount
except Exception as e:
print e
error = e.message
cursor.close()
conn.commit()
except Exception as e:
error = e.message
finally:
if conn:
conn.close()
if count == 0:
return '{"code":%d,"count":%d,"error":"%s"}' % (-1, count, error)
else:
return '{"code":%d,"count":%d,"error":"%s"}' % (0, count, error)
参考Chrome开发文档:developer.chrome.com/extensions/bookmarks
网友评论