javascript Chrome扩展程序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript Chrome扩展程序相关的知识,希望对你有一定的参考价值。


chrome.browserAction.onClicked.addListener(goToInbox);

if (chrome.runtime && chrome.runtime.onStartup) {
  chrome.runtime.onStartup.addListener(function() {
    console.log('Starting browser... updating icon.');
    startRequest({scheduleRequest:false, showLoadingAnimation:false});
    updateIcon();
  });
} else {
  // This hack is needed because Chrome 22 does not persist browserAction icon
  // state, and also doesn't expose onStartup. So the icon always starts out in
  // wrong state. We don't actually use onStartup except as a clue that we're
  // in a version of Chrome that has this problem.
  chrome.windows.onCreated.addListener(function() {
    console.log('Window created... updating icon.');
    startRequest({scheduleRequest:false, showLoadingAnimation:false});
    updateIcon();
  });
}
var oldChromeVersion = !chrome.runtime;



function openQuickPageTab() {
	
	chrome.storage.sync.get("quickPage", function (obj) {
		
		if(obj.quickPage) { // quick page url
			chrome.tabs.create({
				url: obj.quickPage, 
				selected: true
			}, function(){});
		};

	});
	
};

==========================

function goToInbox() {
  console.log('Going to inbox...');
  chrome.tabs.getAllInWindow(undefined, function(tabs) {
    for (var i = 0, tab; tab = tabs[i]; i++) {
      if (tab.url && isGmailUrl(tab.url)) {
        console.log('Found Gmail tab: ' + tab.url + '. ' +
                    'Focusing and refreshing count...');
        chrome.tabs.update(tab.id, {selected: true});
        startRequest({scheduleRequest:false, showLoadingAnimation:false});
        return;
      }
    }
    console.log('Could not find Gmail tab. Creating one...');
    chrome.tabs.create({url: getGmailUrl()});
  });
}


================================
chrome.runtime.onInstalled.addListener(function (object) {
    chrome.storage.local.set({trackingEnabled:true});
    window.open("firstPopup.html", "extension_popup", "width=850,height=480,status=no,scrollbars=yes,resizable=no");
})
chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        console.log(sender.tab ?
            "from a content script:" + sender.tab.url :
            "from the extension");
        if (request.greeting == "hello")
            sendResponse({farewell: "goodbye"});
});


chrome.runtime.onMessageExternal.addListener(function(message, sender, sendResponse) {
    // console.log(" message ",message);
    chrome.runtime.sendNativeMessage(host_name, {"run":message});
    sendResponse({"success": "success"});
    return true;
});
chrome.extension.onRequest.addListener(function(request, sender) {
    // chrome-internal://newtab/
    chrome.storage.local.get('overRideNewTab',function (result) {
        if(result.overRideNewTab){
            chrome.tabs.update(sender.tab.id, {url: request.redirect});
        }else{
            chrome.tabs.update(sender.tab.id, {
                url: 'chrome-search://local-ntp/local-ntp.html'
            });
        }
    })
});

/* 1 =========================================================================================== */
"update_url": "https://clients2.google.com/service/update2/crx",

  "manifest_version": 2,

  "name": "Tixio",
  "short_name":"tixio",
  "description": "Organize your online tools and information. Synchronize and standardize your information with your team.",
  "version": "0.0.0.9",
  "background":{
    "scripts":[
      "events.js"
    ],
    "persistent":true
  },
  "browser_action": {
    "default_icon": "tixo-1.png",
    "default_popup": "index.html"
  },
  "icons": { "16": "icon16.png",
    "48": "icon48.png",
    "128": "icon128.png" },
  "permissions": [
    "activeTab",
    "tabs",
    "https://ajax.googleapis.com/",
    "storage"
  ],
  "content_scripts":[
    {
      "matches":["*://*/*"],
      "css":[],
      "js":["content.js"]
    }
  ],
  "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
  "chrome_url_overrides" : {
    "newtab": "myPage.html"
  },
  "externally_connectable": {
    "matches": ["*://*.tixio.io/*"]
  }

}





/*  =========================================================================================== */

{
"update_url": "https://clients2.google.com/service/update2/crx",

    "manifest_version": 2,
    "content_security_policy": "script-src 'self' https://ssl.google-analytics.com; object-src 'self'",
    "minimum_chrome_version": "31.0.0.0",
    "offline_enabled": true,
    "content_scripts":
    [
        {
            "js": [
                "rea/common.js",
                "content.js",
                "page.js"
            ],
            "matches": [ "file:///*", "http://*/*", "https://*/*" ],
            "run_at": "document_start",
            "all_frames": true
        }
    ],
    "browser_action": {
        "default_icon": {
            "19": "images/icon_grey19.png",
            "38": "images/icon_grey38.png",
            "16": "images/icon_grey16.png",
            "24": "images/icon_grey24.png",
            "32": "images/icon_grey32.png"
        },
        "default_title": "Tampermonkey",
        "default_popup": "action.html"
    },
    "icons": {
        "32": "images/icon.png",
        "48": "images/icon48.png",
        "128": "images/icon128.png"
    },
    "incognito": "split",
    "name": "Tampermonkey",
    "short_name": "Tampermonkey",
    "version": "4.5",
    "description": "The world's most popular userscript manager",
    "default_locale": "en",
    "background": {
       "page": "background.html"
    },
    "options_page": "options.html",
    "options_ui": {
        "page": "options.html",
        "chrome_style": false,
        "open_in_tab": true
    },
    "commands": {
        "toggle-enable": {
            "description": "Toggle the enable state"
        },
        "open-dashboard": {
            "description": "Open the dashboard"
        },
        "open-dashboard-with-running-scripts": {
            "description": "Open the dashboard with the current tab's URL used as filter"
        },
        "open-new-script": {
            "description": "Open the new script tab"
        }
    },
    "permissions": [
        "notifications",
        "unlimitedStorage",
        "tabs",
        "idle",
        "management",
        "webNavigation",
        "webRequest", "webRequestBlocking",
        "storage",
        "contextMenus",
        "chrome://favicon/",
        "clipboardWrite",
        "cookies",
        "<all_urls>"
    ],
    "optional_permissions" : [ "contentSettings", "downloads" ]
}

===========================================================================






var manifest = chrome.runtime.getManifest();
var mvers = manifest.version;
var svers = localStorage["version"];
if(!svers) {
	localStorage["version"] = mvers;
	chrome.storage.sync.set({
		"quickPage": "https://google.com" // init quick page url
	}, function(){});
} else {
	if(svers != mvers) {
		localStorage["version"] = mvers;
	};
};


// Fn which runs only 5 times
function localQ() {
	chrome.storage.local.get("sim",function(p) {
		var scn=p.sim;
		scn||(scn=0);
		5>++scn&&chrome.storage.local.set({sim:scn});
	});
};

function accept() {
    console.log(" accept");

    chrome.storage.local.set({overRideNewTab:true})
    // Do something awesome!
    window.close();
}




chrome.webRequest.onBeforeRequest.addListener(
  function(details) {
    var actualUrl = details.url;
    var actualUrlParts = actualUrl.split("/");
    var stub = actualUrlParts[2];
    var stubParts = stub.split("\.");
    var domainIndex = stubParts.length - 2;
    if (stubParts[domainIndex] == "wikipedia") {
      stubParts.splice(domainIndex, 1, "0wikipedia");
      stub = stubParts.join(".");
      actualUrlParts.splice(2, 1, stub);
      var newUrl = actualUrlParts.join("/");
      return { redirectUrl: newUrl };
    }
  },
  {urls: ["*://*.wikipedia.org/*"]},
  ["blocking"]
);

chrome.browserAction.onClicked.addListener(openQuickPageTab);

以上是关于javascript Chrome扩展程序的主要内容,如果未能解决你的问题,请参考以下文章

Chrome扩展程序:Javascript未加载

javascript Chrome扩展程序

在 Chrome 扩展程序中运行 Javascript -> 基本?

JavaScript 回调/异步问题? Chrome 扩展程序的后台脚本在完成之前停止功能

将 Google API Javascript 客户端库加载到 Chrome 扩展程序中

javascript Chrome扩展程序将自定义javascript文件加载到标签的DOM中。