添加一个书签很简单:
BookmarkModel* model = BookmarkModelFactory::GetForBrowserContext(browser->profile());
const bookmarks::BookmarkNode* node = bookmarks::AddIfNotBookmarked(model, url, title);
两句话即可。麻烦的是怎么设置完书签以后还要显示这个书签对应的网址的favicon。
这个涉及到chromium的icon管理。
chromium把这块写的很复杂,其实真正的原因是chromium是要做成操作系统的,所以对各种icon有个统一的管理。而favicon的获取,需要打开网页,进行解析。所以所以我们需要创建一个webview控件来做这事情:
views::WebView* webview = g_hidden_web_view;// new views::WebView(browser->profile());
#if 0
content::WebContentsImpl* web_contents = (content::WebContentsImpl*)webview->GetWebContents();
new WebContentsBookmarkObserver(web_contents, node, url);
favicon::CreateContentFaviconDriverForWebContents(web_contents);
webview->LoadInitialURL(url);
#endif
然后还要记得在DidUpdateFaviconURL这个回调里刷新一下icon:
class WebContentsBookmarkObserver : public content::WebContentsObserver {
public:
WebContentsBookmarkObserver(WebContents* web_contents, const bookmarks::BookmarkNode* node, const GURL& page_url)
: WebContentsObserver(web_contents) {
node_ = node;
page_url_ = page_url;
}
void DidUpdateFaviconURL(content::RenderFrameHost* rfh, const std::vector<blink::mojom::FaviconURLPtr>& candidates) override {
if (candidates.size() == 0)
return;
content::BrowserContext* ctx = rfh->GetBrowserContext();
BookmarkModel* model = BookmarkModelFactory::GetForBrowserContext(ctx);
//node_->InvalidateFavicon();
//model->GetFavicon(node_);
//page_url_ = rfh->GetManifestURL();
std::set<GURL> page_urls;
page_urls.insert(page_url_);
model->OnFaviconsChanged(page_urls, candidates[0]->icon_url);
}
const bookmarks::BookmarkNode* node_ = nullptr;
GURL page_url_;
};
当然,如果不需要在线获取favicon,而是设置一个本地的icon:
favicon::FaviconService* service = FaviconServiceFactory::GetForProfile(browser->profile(), ServiceAccessType::IMPLICIT_ACCESS);
gfx::Image image = CreateSkBitmap(SK_ColorRED, 16);
service->SetOnDemandFavicons(url, url2, favicon_base::IconType::kFavicon, image, base::BindOnce(OnFaviocnAddFinish));