Google chrome 创建自己的chrome扩展:如何获取书签和打开本地html文件

Google chrome 创建自己的chrome扩展:如何获取书签和打开本地html文件,google-chrome,google-chrome-extension,favicon,bookmarks,local-files,Google Chrome,Google Chrome Extension,Favicon,Bookmarks,Local Files,这是我创建的第一个Chrome扩展。我需要一个简化的、速度更快的书签侧面板。我设法列出了我的chrome书签,最后做了一些真正深入的搜索,以了解如何打开本地URL“file://”。我必须创建一个content.js文件,所以这是解决方案的一部分,但它不是完整的 我仍然没有找到如何加载chrome存储在缓存中的favicon。我真的很想有人在这方面帮助我 在解决上一个问题时,我遇到了一个新问题,我的div并不总是在everypage上创建,甚至有时会因为某种原因消失或变为空,请注意,本地文件再次

这是我创建的第一个Chrome扩展。我需要一个简化的、速度更快的书签侧面板。我设法列出了我的chrome书签,最后做了一些真正深入的搜索,以了解如何打开本地URL“file://”。我必须创建一个content.js文件,所以这是解决方案的一部分,但它不是完整的

我仍然没有找到如何加载chrome存储在缓存中的favicon。我真的很想有人在这方面帮助我

在解决上一个问题时,我遇到了一个新问题,我的div并不总是在everypage上创建,甚至有时会因为某种原因消失或变为空,请注意,本地文件再次出现,但我的content.js脚本运行。我不知道为什么会发生这种事

以下是每个文件的源代码:

manifest.json:

    {
        "name": "Favorites Sidebar",
        "version": "0.0.0.1",
        "manifest_version": 2,
        "description": "Displays a sidebar with the list of your favorites.",
        "icons": {
            "16": "icons/favorites16.png",
            "32": "icons/favorites32.png",
            "48": "icons/favorites48.png",
            "128": "icons/favorites128.png"
        },
        "background": {
            "scripts": ["background.js"],
            "persistent": false
        },
        "content_scripts": [
            {
                "matches": ["<all_urls>"],
                "css": ["style.css"],
                "js": ["content.js"]
            }
        ],
        "permissions": [
            "activeTab",
            "*://*/*",
            "bookmarks"
        ]
    }
    var scode = "";
    var fav_list = "";
    var sfullbody = "";

    var sicondir = "<div style=\\\"padding: 0; margin: 1px 4px 1px 4px; display: inline-block;\\\">";
    sicondir += "<div style=\\\"position: relative; width: 8px; height: 2px; border-radius: 3px 3px 0 0; background-color: #C19536; padding: 0; margin: 0;\\\"></div>";
    sicondir += "<div style=\\\"position: relative; width: 16px; height: 10px; border-radius: 0 3px 3px 3px; background-color: #C19536; padding: 0; margin: 0;\\\"></div>";
    sicondir += "</div>";

    var jvshowdir = "var odir = document.getElementById(\\'%dirname%\\');";
    jvshowdir += "var sdisp = odir.style.display;";
    jvshowdir += "if (sdisp == \\'block\\') {";
    jvshowdir += "odir.style.display = \\'none\\';} else {";
    jvshowdir += "odir.style.display = \\'block\\';}";

    var ilogcnt = 0;
    var curtid = 0;
    var cururl = "";

    chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
        console.log("message.url:"+message.url);
        console.log("sender:"+sender.id);
        chrome.tabs.getSelected(null,function (tab) {
            curtid = tab.id;
        });
        console.log(curtid);
        chrome.tabs.update(message);
    });

    chrome.tabs.onUpdated.addListener(
        function(tabId, changeInfo, tab) {

            chrome.bookmarks.getTree(GetFavs);
            
            scode += "var pdiv = document.getElementById('daric-fav-overlay');";
            scode += "var odiv = -1;";
            scode += "if (!pdiv) {";
            scode += "var odiv = document.createElement('div');";
            scode += "} else {";
            scode += "odiv = pdiv;";
            scode += "odiv.innerHTML = '';";
            scode += "}";
            scode += "odiv.id = 'daric-fav-overlay';";
            scode += "odiv.innerHTML = \""+fav_list+"\";";
            scode += "document.body.insertAdjacentElement('afterbegin',odiv);";
            
            chrome.tabs.executeScript(
                null,
                {code: scode}
            )
            
        }
    );

    function GetFavs(treeItem,subDir="",FirstItem = true) {
        var ictr = 0;
        var ofav = -1;
        var sitem = "";
        var stitle = "";
        var stmp = "";
        var surl = "";
        var itlen = 0;
        var iclen = 0;
        var sjvdc = "";
        var sdash = "";
        var item1 = FirstItem;
        
        itlen = treeItem.length;
        
        // Loop all favorites
        for (ictr = 0; ictr < itlen; ictr ++) {
            ofav = treeItem[ictr];
            iclen = 0;
            if (ofav.children) {iclen = ofav.children.length;}
            
            // Get favorite's title if any
            if (ofav.title != "") {
                stitle = ofav.title;
                stitle = stitle.replace(/\'/g,"\\'");
                stitle = stitle.replace(/\"/g,"\\\"");
            }
            
            // Get children list
            if (iclen > 0 || typeof ofav.url === "undefined") {
                // Show favorite's title
                if (ofav.title != "") {
                    // Replace spaces by dash
                    stmp = stitle;
                    stmp = stmp.replace(/ /g,"-");
                    // Build directory clickable menu
                    sjvdc = jvshowdir;
                    sjvdc = sjvdc.replace(/%dirname%/g,stmp);
                    // Do not set the root folder as a clickable folder
                    sitem = "<div style=\\\"font-weight: bold; font-style: italic;margin: 4px 0 0 4px; padding: 0;\\\">"+stitle+"</div><div class=\\\"root-list\\\">";
                    if (item1 == false) {
                        sitem = "<div class=\\\"daric-folder\\\" id=\\\"dir-"+stmp+"\\\" onclick=\\\""+sjvdc+"\\\">";
                        sitem += sicondir+stitle+"</div><div class=\\\"daric-sub-folder\\\" style=\\\"display: none;\\\" id=\\\""+stmp+"\\\">";
                    }
                    // Make sure to only add different folders
                    if (!fav_list.includes(sitem)) {fav_list += sitem;}
                    item1 = false;
                }
                // Get children list
                if (subDir != "") {sdash = "--";}
                GetFavs(ofav.children,subDir+sdash+stmp,item1);
                fav_list += "</div>";
            } else {
                // No children found, this is probably a bookmark link
                surl = ofav.url;
                // Create a valid ID from title
                sdash = subDir+"-"+Dashify(stitle);
                // Check if item already exists;
                if (!fav_list.includes(sdash)) {
                    //if (fav_list.includes(sdash)) {sdash += "-"+Math.floor(Math.random()*100000).toString();}
                    sitem = "<div class=\\\"daric-fav\\\" id=\\\""+sdash+"\\\">&nbsp;&nbsp;"+stitle+"</div>";
                    sitem += "<input id=\\\"daric-url-"+sdash+"\\\" class=\\\"daric-hidden\\\" type=\\\"text\\\" value=\\\""+surl+"\\\"/>";
                    fav_list += sitem;
                }
            }
            
        }
    }

    // Replace numourous possible troublesome characters to dashes "-"
    // Good for class or id names
    function Dashify (sString) {
        var sdash = sString;
        
        sdash = sdash.replace(/ /g,"-");
        sdash = sdash.replace(/\"/g,"-");
        sdash = sdash.replace(/\'/g,"-");
        sdash = sdash.replace(/\:/g,"-");
        sdash = sdash.replace(/\(/g,"-");
        sdash = sdash.replace(/\)/g,"-");
        sdash = sdash.replace(/\[/g,"-");
        sdash = sdash.replace(/\]/g,"-");
        sdash = sdash.replace(/\{/g,"-");
        sdash = sdash.replace(/\}/g,"-");
        sdash = sdash.replace(/\./g,"-");
        sdash = sdash.replace(/\,/g,"-");
        sdash = sdash.replace(/\;/g,"-");
        sdash = sdash.replace(/\</g,"-");
        sdash = sdash.replace(/\>/g,"-");
        sdash = sdash.replace(/\?/g,"-");
        sdash = sdash.replace(/\!/g,"-");
        sdash = sdash.replace(/\%/g,"-");
        sdash = sdash.replace(/\^/g,"-");
        sdash = sdash.replace(/\$/g,"-");
        sdash = sdash.replace(/\#/g,"-");
        sdash = sdash.replace(/\@/g,"-");
        sdash = sdash.replace(/\*/g,"-");
        sdash = sdash.replace(/\&/g,"-");
        sdash = sdash.replace(/\~/g,"-");
        
        return sdash;
    }
    var sid_down = "";
    var sid_up = "";

    document.addEventListener("mousedown",function(e){
        sid_down = "daric-url-"+e.target.id;
    },false);

    document.addEventListener("mouseup",function(e){
        sid_up = "daric-url-"+e.target.id;
        // send message ONLY if we mouseup on the same element
        if (sid_up == sid_down && typeof document.getElementById(sid_up) !== "undefined") {
            chrome.runtime.sendMessage({url: document.getElementById(sid_up).value});
        }
    },false);
    #daric-fav-overlay {
        background-color: rgba(0,0,0,0);
        color: rgba(0,0,0,0);
        position: fixed;
        display: inline-block;
        white-space: nowrap;
        font-family: Arial;
        left: 0;
        top: 0;
        width: 4px;
        height: 100%;
        margin: 0;
        border: 0;
        padding: 0;
        overflow: hidden;
        z-index: 9000000;
        cursor: default;
        -ms-user-select: none;
        user-select: none;
    }
    #daric-fav-overlay:hover {
        color: #DFDFDF;
        width: auto;
        overflow: auto;
        background-color: rgba(0,0,0,0.8);
    }

    .daric-folder:hover, .daric-fav:hover {
        background-color: rgba(255,255,255,0.2);
    }

    .daric-folder, .daric-sub-folder {
        cursor: default;
        padding: 4px;
        margin: 0;
        white-space: nowrap;
    }

    .daric-fav {
        cursor: default;
        padding: 4px;
        margin: 0;
    }

    .daric-hidden {
        width: 0;
        height: 0;
        padding: 0;
        margin: 0;
        border: 0;
        top: -400px;
        left: -400px;
        position: fixed;
    }
style.css:

    {
        "name": "Favorites Sidebar",
        "version": "0.0.0.1",
        "manifest_version": 2,
        "description": "Displays a sidebar with the list of your favorites.",
        "icons": {
            "16": "icons/favorites16.png",
            "32": "icons/favorites32.png",
            "48": "icons/favorites48.png",
            "128": "icons/favorites128.png"
        },
        "background": {
            "scripts": ["background.js"],
            "persistent": false
        },
        "content_scripts": [
            {
                "matches": ["<all_urls>"],
                "css": ["style.css"],
                "js": ["content.js"]
            }
        ],
        "permissions": [
            "activeTab",
            "*://*/*",
            "bookmarks"
        ]
    }
    var scode = "";
    var fav_list = "";
    var sfullbody = "";

    var sicondir = "<div style=\\\"padding: 0; margin: 1px 4px 1px 4px; display: inline-block;\\\">";
    sicondir += "<div style=\\\"position: relative; width: 8px; height: 2px; border-radius: 3px 3px 0 0; background-color: #C19536; padding: 0; margin: 0;\\\"></div>";
    sicondir += "<div style=\\\"position: relative; width: 16px; height: 10px; border-radius: 0 3px 3px 3px; background-color: #C19536; padding: 0; margin: 0;\\\"></div>";
    sicondir += "</div>";

    var jvshowdir = "var odir = document.getElementById(\\'%dirname%\\');";
    jvshowdir += "var sdisp = odir.style.display;";
    jvshowdir += "if (sdisp == \\'block\\') {";
    jvshowdir += "odir.style.display = \\'none\\';} else {";
    jvshowdir += "odir.style.display = \\'block\\';}";

    var ilogcnt = 0;
    var curtid = 0;
    var cururl = "";

    chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
        console.log("message.url:"+message.url);
        console.log("sender:"+sender.id);
        chrome.tabs.getSelected(null,function (tab) {
            curtid = tab.id;
        });
        console.log(curtid);
        chrome.tabs.update(message);
    });

    chrome.tabs.onUpdated.addListener(
        function(tabId, changeInfo, tab) {

            chrome.bookmarks.getTree(GetFavs);
            
            scode += "var pdiv = document.getElementById('daric-fav-overlay');";
            scode += "var odiv = -1;";
            scode += "if (!pdiv) {";
            scode += "var odiv = document.createElement('div');";
            scode += "} else {";
            scode += "odiv = pdiv;";
            scode += "odiv.innerHTML = '';";
            scode += "}";
            scode += "odiv.id = 'daric-fav-overlay';";
            scode += "odiv.innerHTML = \""+fav_list+"\";";
            scode += "document.body.insertAdjacentElement('afterbegin',odiv);";
            
            chrome.tabs.executeScript(
                null,
                {code: scode}
            )
            
        }
    );

    function GetFavs(treeItem,subDir="",FirstItem = true) {
        var ictr = 0;
        var ofav = -1;
        var sitem = "";
        var stitle = "";
        var stmp = "";
        var surl = "";
        var itlen = 0;
        var iclen = 0;
        var sjvdc = "";
        var sdash = "";
        var item1 = FirstItem;
        
        itlen = treeItem.length;
        
        // Loop all favorites
        for (ictr = 0; ictr < itlen; ictr ++) {
            ofav = treeItem[ictr];
            iclen = 0;
            if (ofav.children) {iclen = ofav.children.length;}
            
            // Get favorite's title if any
            if (ofav.title != "") {
                stitle = ofav.title;
                stitle = stitle.replace(/\'/g,"\\'");
                stitle = stitle.replace(/\"/g,"\\\"");
            }
            
            // Get children list
            if (iclen > 0 || typeof ofav.url === "undefined") {
                // Show favorite's title
                if (ofav.title != "") {
                    // Replace spaces by dash
                    stmp = stitle;
                    stmp = stmp.replace(/ /g,"-");
                    // Build directory clickable menu
                    sjvdc = jvshowdir;
                    sjvdc = sjvdc.replace(/%dirname%/g,stmp);
                    // Do not set the root folder as a clickable folder
                    sitem = "<div style=\\\"font-weight: bold; font-style: italic;margin: 4px 0 0 4px; padding: 0;\\\">"+stitle+"</div><div class=\\\"root-list\\\">";
                    if (item1 == false) {
                        sitem = "<div class=\\\"daric-folder\\\" id=\\\"dir-"+stmp+"\\\" onclick=\\\""+sjvdc+"\\\">";
                        sitem += sicondir+stitle+"</div><div class=\\\"daric-sub-folder\\\" style=\\\"display: none;\\\" id=\\\""+stmp+"\\\">";
                    }
                    // Make sure to only add different folders
                    if (!fav_list.includes(sitem)) {fav_list += sitem;}
                    item1 = false;
                }
                // Get children list
                if (subDir != "") {sdash = "--";}
                GetFavs(ofav.children,subDir+sdash+stmp,item1);
                fav_list += "</div>";
            } else {
                // No children found, this is probably a bookmark link
                surl = ofav.url;
                // Create a valid ID from title
                sdash = subDir+"-"+Dashify(stitle);
                // Check if item already exists;
                if (!fav_list.includes(sdash)) {
                    //if (fav_list.includes(sdash)) {sdash += "-"+Math.floor(Math.random()*100000).toString();}
                    sitem = "<div class=\\\"daric-fav\\\" id=\\\""+sdash+"\\\">&nbsp;&nbsp;"+stitle+"</div>";
                    sitem += "<input id=\\\"daric-url-"+sdash+"\\\" class=\\\"daric-hidden\\\" type=\\\"text\\\" value=\\\""+surl+"\\\"/>";
                    fav_list += sitem;
                }
            }
            
        }
    }

    // Replace numourous possible troublesome characters to dashes "-"
    // Good for class or id names
    function Dashify (sString) {
        var sdash = sString;
        
        sdash = sdash.replace(/ /g,"-");
        sdash = sdash.replace(/\"/g,"-");
        sdash = sdash.replace(/\'/g,"-");
        sdash = sdash.replace(/\:/g,"-");
        sdash = sdash.replace(/\(/g,"-");
        sdash = sdash.replace(/\)/g,"-");
        sdash = sdash.replace(/\[/g,"-");
        sdash = sdash.replace(/\]/g,"-");
        sdash = sdash.replace(/\{/g,"-");
        sdash = sdash.replace(/\}/g,"-");
        sdash = sdash.replace(/\./g,"-");
        sdash = sdash.replace(/\,/g,"-");
        sdash = sdash.replace(/\;/g,"-");
        sdash = sdash.replace(/\</g,"-");
        sdash = sdash.replace(/\>/g,"-");
        sdash = sdash.replace(/\?/g,"-");
        sdash = sdash.replace(/\!/g,"-");
        sdash = sdash.replace(/\%/g,"-");
        sdash = sdash.replace(/\^/g,"-");
        sdash = sdash.replace(/\$/g,"-");
        sdash = sdash.replace(/\#/g,"-");
        sdash = sdash.replace(/\@/g,"-");
        sdash = sdash.replace(/\*/g,"-");
        sdash = sdash.replace(/\&/g,"-");
        sdash = sdash.replace(/\~/g,"-");
        
        return sdash;
    }
    var sid_down = "";
    var sid_up = "";

    document.addEventListener("mousedown",function(e){
        sid_down = "daric-url-"+e.target.id;
    },false);

    document.addEventListener("mouseup",function(e){
        sid_up = "daric-url-"+e.target.id;
        // send message ONLY if we mouseup on the same element
        if (sid_up == sid_down && typeof document.getElementById(sid_up) !== "undefined") {
            chrome.runtime.sendMessage({url: document.getElementById(sid_up).value});
        }
    },false);
    #daric-fav-overlay {
        background-color: rgba(0,0,0,0);
        color: rgba(0,0,0,0);
        position: fixed;
        display: inline-block;
        white-space: nowrap;
        font-family: Arial;
        left: 0;
        top: 0;
        width: 4px;
        height: 100%;
        margin: 0;
        border: 0;
        padding: 0;
        overflow: hidden;
        z-index: 9000000;
        cursor: default;
        -ms-user-select: none;
        user-select: none;
    }
    #daric-fav-overlay:hover {
        color: #DFDFDF;
        width: auto;
        overflow: auto;
        background-color: rgba(0,0,0,0.8);
    }

    .daric-folder:hover, .daric-fav:hover {
        background-color: rgba(255,255,255,0.2);
    }

    .daric-folder, .daric-sub-folder {
        cursor: default;
        padding: 4px;
        margin: 0;
        white-space: nowrap;
    }

    .daric-fav {
        cursor: default;
        padding: 4px;
        margin: 0;
    }

    .daric-hidden {
        width: 0;
        height: 0;
        padding: 0;
        margin: 0;
        border: 0;
        top: -400px;
        left: -400px;
        position: fixed;
    }
预览当前结果。 将鼠标悬停在网页左侧时出现的侧边栏:


1)向我们显示准确的错误消息,并指出发生错误的源行。2) 显示manifest.json的
权限
。3) 用于favicons问题。我已添加manifest.json文件内容。如果此代码在扩展页中运行,则可以使用
chrome.tabs.create({url:'..'})
而不是
window.open
。这很有趣。但是扩展页面拒绝在我这样做时加载边栏。我还希望书签的行为像真实的书签一样,只需在当前选项卡中加载页面。除非有人有另一种方法来创建一个边栏,在网页上创建一个新元素,否则我会选择其他方法。我关注了关于扩展创建的在线帮助,并想到了这个创建边栏的方法。1)这个“边栏”是什么,你是如何创建的?2) 要在当前选项卡中打开内容,请使用
chrome.tabs.update
1)向我们显示准确的错误消息,并指明发生错误的源行。2) 显示manifest.json的
权限
。3) 用于favicons问题。我已添加manifest.json文件内容。如果此代码在扩展页中运行,则可以使用
chrome.tabs.create({url:'..'})
而不是
window.open
。这很有趣。但是扩展页面拒绝在我这样做时加载边栏。我还希望书签的行为像真实的书签一样,只需在当前选项卡中加载页面。除非有人有另一种方法来创建一个边栏,在网页上创建一个新元素,否则我会选择其他方法。我关注了关于扩展创建的在线帮助,并想到了这个创建边栏的方法。1)这个“边栏”是什么,你是如何创建的?2) 要在当前选项卡中打开内容,请使用
chrome.tabs.update