jQuery轉發插件小記

動機: 國內外許多網站都會使用谷歌CDN的jQuery: https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js,不翻牆的話訪問不到。之前在360極速瀏覽器的商店裏面看到了個CDN轉發器,能夠將jQuery重定向到百度的jQuery庫裏面,但是已經不能在新版的chrome上運行了,因此參考chrome擴展的API仿照做了個。

擴展文件結構:

  • manifest.json - 清單文件,包括權限,圖標等信息
    {
        "name": "jQuery轉發",
        "version": "1.0",
        "description": "將從谷歌cdn獲取的jQuery更改爲從百度cdn獲取",
        "permissions": [
            "declarativeContent",
            "activeTab",
            "webRequest",
            "http://*/*",
            "https://*/*",
            "webRequestBlocking"
        ],
        "background": {
            "scripts": [
                "background.js"
            ],
            "persistent": true
        },
        "page_action":{
            "default_popup": "popup.html"
        },
        "icons":{
            "128":"icon_128.png"
        },
        "manifest_version": 2
    }
    
  • background.js - 註冊事件處理程序文件,如網頁發起請求的onBeforeRequest事件
    chrome.webRequest.onBeforeRequest.addListener(
        function (details) {
            var url = details.url;
            if (url.indexOf("//ajax.googleapis.com/ajax/libs/jquery/") > -1) {
                console.log('change cdn');
                var urls = url.split('/');
                if (urls[urls.length - 2].length <= 3) {
                    urls[urls.length - 2] += '.0';
                }
                var newUrl = urls[0] + '//cdn.bootcss.com/jquery/' + urls  [urls.length - 2] + '/jquery.min.js';
                console.log(newUrl);
                return { redirectUrl: newUrl };
            }
            return { cancel: false };
        },
        {
            urls: ["<all_urls>"],
            types: ["script"]
        },
        ["blocking"]
    );
    
  • icon_128.png(可選)

然後使用瀏覽器的加載已解壓的擴展程序選擇文件夾加載擴展程序就可以使用了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章