Saturday, May 14, 2016

Chrome Extension



Chrome插件英雄榜
https://zhaoolee.gitbooks.io/chrome/content/010-speedtest300b-wang-luo-ce-su-cha-jian-speedtest.html

https://www.tampermonkey.net/scripts.php
OpenUserJS started right after GreasyFork. It is created by Sizzle McTwizzle and has a lot of scripts in its inventory.
GreasyFork is maybe the most popular newcomer. It has many scripts in its inventory and is created by Jason Barnabe, the author of Stylish.
https://www.lifewire.com/top-greasemonkey-tampermonkey-user-scripts-4134335

https://stackoverflow.com/questions/17168395/including-a-greasemonkey-script-across-multiple-domains
https://wiki.greasespot.net/Include_and_exclude_rules
// @include     http://www.example.com/foo/*
// @include     http://www.example.org/*.bar
// @exclude     http://www.example.com/foo/baz


https://developer.chrome.com/apps/commands
By default, Commands are scoped to the Chrome browser, which means that while the browser does not have focus, the shortcut will be inactive. On desktop Chrome, Commands can instead have global scope, as of version 35, and will then also work while Chrome does *not* have focus. NOTE: The exception here is Chrome OS, where global commands are not allowed at the moment.
The user is free to designate any shortcut as global using the UI in chrome://extensions \ Keyboard Shortcuts, but the extension developer is limited to specifying only Ctrl+Shift+[0..9] as global shortcuts. This is to minimize the risk of overriding shortcuts in other applications since if, for example, Alt+P were to be allowed as global, the printing shortcut might not work in other applications.
https://apple.stackexchange.com/questions/108060/how-to-prevent-command-i-command-shift-i-from-opening-mac-mail-when-in-browser
  1. Install the Chrome extension Shortkeys.
  2. Open the Shortkeys's preference panel, add a command+shift+i shortcut like below:
Disable command+shift+i(send email), command+shift+f(Always show toolbar in full screen)
Activation Settings -> All Sites
https://superuser.com/questions/693664/how-to-get-new-tab-link-opened-on-the-right-of-the-current-tabs-in-chrome-web-br
How to get new tab/link opened on the right of the current tabs in Chrome web browser?
I use Tab Position Customizer 2 for this. When you bring up the options for this extension, the first set of options, titled "Tab Opening Position" allows you to set where new tabs open.
https://github.com/t9md/atom-vim-mode-plus/issues/130
To open the keymap.cson file, go to settings>keybindings>"your keymap file"
#keymap.cson
'atom-text-editor.vim-mode-plus.insert-mode':
  # Case-5: keydown both `left-cmd` and `right-cmd` then release
  # Good: simple, no delay when you insert characters in insert-mode. Less accidental escaping.
  # Bad: You need to use both left and right thumb.
  'cmd ^cmd ^cmd': 'vim-mode-plus:activate-normal-mode'
https://coderwall.com/p/lhsrcq/one-line-browser-notepad
data:text/html, <html contenteditable>
We are using the Data URI's format and telling the browser to render an html (try "javascript:alert('Bazinga');"). The content of said html is a simple html line with the html5 attribute contenteditable. This works only on modern browsers that understand this attribute

https://kurttappe.com/2017/05/15/whitelisting-unsecure-websites-in-recent-versions-of-chrome-for-macos/
http://www.chromium.org/administrators/policy-list-3#CertificateTransparencyEnforcementDisabledForUrls
The latest versions of Chrome (from v57 forward I believe) perform extra checking on websites. This may lead you to encounter “Your connection is not private” and “NET::ERR_CERTIFICATE_TRANSPARENCY_REQUIRED” warnings when visiting sites that are known safe.

What generates the alert is that not all companies (mine included) implement our web certificates the way Chrome now expects. Something to do with Chrome and OpenSSL using different trusted root CA’s which makes the trust chain slightly different. To be fair, Chrome now checks this to prevent spoofing and MIM attacks, but it results in false errors and causes Chrome to stop offering to store passwords. Annoying.

To whitelist a domain in Chrome, ensure the com.google.chrome.plist file in /Library/Preferences contains:
<key>CertificateTransparencyEnforcementDisabledForUrls</key>
<array>
  <string>[your.domain]</string>
  <string>[your.domain2]</string>
  <string>[your.domain3]</string>
</array>
You can put as many or as few entries in the array as you like.
Note: Before you try to view com.google.chrome.plist, be aware it is in binary mode. Use this command to convert it to human-readable format:
plutil -convert xml1 com.google.Chrome.plist


The AuthNegotiateDelegateWhitelist key should be persistent and survive Chrome updates. The plist conversion to xml will not.

Visual mode implements a number of vim-like movements, j, k, h, l, w, e, b, etc. Counts are also supported, for example 3e.
https://docs.oracle.com/cd/E19253-01/806-7612/6jgfmsvqf/index.html

  • To move left, press h.
  • To move right, press l.
  • To move down, press j.
  • To move up, press k.

Moving One Word

Press w (“word”) to move the cursor to the right one word at a time.
Press b (“back”) to move the cursor to the left one word at a time.
Press W or B to move the cursor past the adjacent punctuation to the next or previous blank space.
Press e (“end”) to move the cursor to the last character of the current word.

Moving to Start or End of Line

Press ^ to move the cursor to the start of the current line.

Press $ to move the cursor to the end of the current line.

https://stackoverflow.com/questions/28786723/why-doesnt-chrome-tabs-query-return-the-tabs-url-when-called-using-requirejs
var activeTabId;

chrome.tabs.onActivated.addListener(function(activeInfo) {
  activeTabId = activeInfo.tabId;
});

function getActiveTab(callback) {
  chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
    var tab = tabs[0];

    if (tab) {
      callback(tab);
    } else {
      chrome.tabs.get(activeTabId, function (tab) {
        if (tab) {
          callback(tab);
        } else {
          console.log('No active tab identified.');
        }
      });

    }
  });
}

https://chrome.googleblog.com/2010/09/tip-just-text-please.html
**Command-Shift-Option-V** |**Paste without formatting**

https://www.lifewire.com/top-greasemonkey-tampermonkey-user-scripts-4134335
This script can prove very useful to programmers by resizing all GitHub repository pages for a better look and feel.

Disable Download Bar
https://chrome.google.com/webstore/detail/disable-download-bar/epnnapjdpplekmodajomjojfpeicclep/related

chrome://flags/

https://stackoverflow.com/questions/26415925/chrome-tabs-getcurrent-or-tabs-query
Cannot use chrome.tabs in content script,you need to use chrome.runtime To know the tab id of the content script, first use chrome.runtime.sendMessage to send a message, and the background page receive it.
Using chrome.runtime.onMessage.addListener, the callback function is
function(any message, MessageSender sender, function sendResponse) {...};
so, you will know the tab id by sender.id
https://stackoverflow.com/questions/15034859/chrome-tabs-returns-undefined-in-content-script
As content script has its own limitations,
chrome.tabs is only available in background scripts and popup scripts.
If you wanna to use chrome.tabs then pass message from content_script to background script and play with chrome.tabs.
Content scripts have only limited access to Chrome APIs. This access does not include the API you are trying to use (e.g. chrome.tabs). If you need to use that API, you will have to do so in a background script1.
As listed in Chrome's content scripts documentation, the APIs available to a content script are [I have placed deprecated methods in
strikethrough format]:

Partition your extension into background scripts and content scripts

You are going to need to separate your code into what needs to be in a background script and what needs to be in content scripts, based on the capabilities available to each type of script. Content scripts have access to the DOM of the web page into which they are injected, but limited access to extension APIs. Background scripts have full access to the extension APIs, but no access to web page content. You should read the Chrome extension overview, and the pages linked from there, to get a feel for what functionality should be located in which type of script.

http://searene.me/2015/12/09/get-selected-text-in-chrome/
Get Selected Text In Chrome
You need this file to inject your script into the target webpage. Without this file, it’s impossible to get the selected text.



















chrome.runtime.sendMessage({
'title': document.title,
'url': window.location.href,
'summary': window.getSelection().toString()
});
https://stackoverflow.com/questions/14452777/is-that-possible-calling-content-script-method-by-context-menu-item-in-chrome-ex
Is that possible calling content script method by context menu item in Chrome extension?


https://stackoverflow.com/questions/16034279/invalid-value-error-while-brackets-in-chrome-commands
Only uppercase letters (A-Z) and digits (0-9) are valid values, as you can see by looking at the source code of the chrome.commands API.
If you want to use other characters, inject a content script in every page which binds a keydownevent:
document.addEventListener('keydown', function(event) {
    if (!event.ctrlKey && event.altKey && event.which === 80/*P*/) {
        // Dispatch a custom message, handled by your extension
        chrome.runtime.sendMessage('Alt+P');
    }
}, true); // <-- True is important

Disadvantages of this method

  • Keyboard focus must be within a page where the content script is activated. The shortcut will fail if you're inside the Developer tools, omnibar, etc.
  • Even if you use <all_urls> as a match pattern, it won't work on non http(s) / file / ftp(s) schemes like chrome:data:chrome-extension:about: or the Chrome Web store.
  • You can run into problems with detecting the [ character, if the keyboard layout does not support it, or uses a different key code.
  • There's no built-in support for customizing this shortcut (as a user, visit chrome://extensions/, scroll to the bottom and click on "Configure commands" to change the extension's shortcut).
https://stackoverflow.com/questions/36348559/chrome-extension-disable-blocking-of-mixed-content
 Mixed Content: The page at 'https://www.instagram.com/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint. This request has been blocked; the content must be served over HTTPS.
There's not such a thing as "pass a parameter to a file".
What you can do is to either insert a content script before executing the file, or sending a message after inserting the file. I will show an example for these distinct methods below.

Set parameters before execution of the JS file

If you want to define some variables before inserting the file, just nest chrome.tabs.executeScript calls:
chrome.tabs.executeScript(tab.id, {
    code: 'var config = 1;'
}, function() {
    chrome.tabs.executeScript(tab.id, {file: 'content.js'});
});
https://stackoverflow.com/questions/36348559/chrome-extension-disable-blocking-of-mixed-content
If you send http request from content scripts, since it lives in the same context with the webpage, it will be restricted by SOP, which is browser behavior.
You could move your http request from content scripts to background page (either by Message Passing or some other trigger like browser Action), since background page lives in the context of the extension, while extension itself can bypass the SOP by adding server URL to permissions.
https://developer.chrome.com/apps/messaging
Communication between extensions and their content scripts works by using message passing. Either side can listen for messages sent from the other end, and respond on the same channel. A message can contain any valid JSON object (null, boolean, number, string, array, or object). 

Sending a request from a content script looks like this:
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
  console.log(response.farewell);
});
Sending a request from the extension to a content script looks very similar, except that you need to specify which tab to send it to. This example demonstrates sending a message to the content script in the selected tab.
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
    console.log(response.farewell);
  });
});

On the receiving end, you need to set up an runtime.onMessage event listener to handle the message. This looks the same from a content script or extension page.

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"});
  });
In the above example, sendResponse was called synchronously. If you want to asynchronously use sendResponse, add return true; to the onMessage event handler.

https://developer.chrome.com/apps/commands
The '_execute_browser_action' and '_execute_page_action' commands are reserved for the action of opening your extension's popups. They won't normally generate events that you can handle. If you need to take action based on your popup opening, consider listening for an 'onDomReady' event inside your popup's code.

chrome://settings/content/notifications?search=Notifications

https://www.pcmag.com/feature/323996/29-hidden-chrome-features-that-will-make-your-life-easier/3
Drag Multiple Tabs at Once
If you're on a Mac, hold the Command key.

Open a Search in New Tab
Hold down the Alt button and hit return on your search and this will open in a new tab. Mac users, press the Command button instead.


Command + 1, 9 to browse tabs
Open Specific Pages at Start
In the Settings menu, go to the section "On Startup" (or just type chrome://settings/startup


https://browsernative.com/extensions/change-chrome-extensions-keyboard-shortcuts/
chrome://extensions/shortcuts
chrome://about/
https://www.ghacks.net/2012/09/04/list-of-chrome-urls-and-their-purpose/
https://gist.github.com/KamranMackey/4bec5630e040be4dcbbe460bb5a1a0ad
chrome://restart/

https://chrome.google.com/webstore/detail/shortkeys-custom-keyboard/logpjaacgmcbpdkdchjiaagddngobkck?hl=en
Shortkeys (Custom Keyboard Shortcuts)

https://www.cnet.com/how-to/21-chrome-shortcuts-you-need-to-know/

When you are viewing a page (and not filling out a form, using Google Docs or otherwise engaging your cursor in Chrome), hit the spacebar to page down on a page and Shift-spacebar to page up.
Use Command-Shift-J to view the files you downloaded with Chrome in a new tab. Again, this one is Mac-only.
https://www.quora.com/What-are-the-most-innovative-Chrome-extensions
  1. Hola Better Internet – “This video is not available in your country”? Use Hola to watch YouTube videos, Netflix, news sites without getting blocked because of your location.
Weava Highlighter - PDF & Web
https://chrome.google.com/webstore/detail/weava-highlighter-pdf-web/cbnaodkpfinfiipjblikofhlhlcickei/related
Citrio is a web-browser based on Chrome. It's not an extension, but if you need a better download manager for Chrome, this is your best option. It speed-up downloads and can download torrent files.


"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --enable-dom-distiller

https://fieldguide.gizmodo.com/how-to-block-super-annoying-website-notification-reques-1797499616
  1. Click Chrome > Preferences, or just paste chrome://settings/content/notifications into your browser to skip steps 2-4.
  2. Scroll down and click Advanced
  3. Click content settings
  4. Click Notifications
  5. Next to the Ask before sending (recommended) text, click the toggle button. It should now say Blocked.
Google Dictionary
https://chrome.google.com/webstore/detail/google-dictionary-by-goog/mgijmajocgfcbeboacabfgobmjgjcoja/related?hl=en

https://www.tomsguide.com/us/pictures-story/283-best-google-chrome-extensions.html#s22
The Great Suspender comes to the rescue by monitoring your open tabs and automatically (or manually) unloading tabs that haven't been used in a while from memory, while retaining the tab's title and favicon on your tab bar. Users can then quickly reload the tab by clicking on the screen.

Turn Off The Lights

At its simplest, you can set Turn Off The Lights to automatically dim your window background when using YouTube or other video sites. If you want to get more in-depth, you can customize the add-on to set custom colors to your screen while playing videos, set atmospheric lighting, fade effects and toggle a night mode for an experience that's more akin to a home theater than a run-of-the-mill video site.

https://www.liutf.com/posts/3720794851.html
  1. Insight.io for Github
    IDE like code intelligence and code search for GitHub by Insight.io.
    Github内看代码更方便,带高亮、跳转。
  2. GitZip for github
    It can make the sub-directories and files of github repository as zip and download it.
    不想Clone整个项目,只想下载单个文件或者单个文件夹时,用这个。
  3. Clear Cache
    一键清除缓存,可以少点很多步。
  4. User-Agent Switcher for Chrome
    Chrome可以转换为别的浏览器进行访问,如IE、Safari、360甚至iOS、 Android等移动浏览器,方便用户进行测试。


CheckChrome
https://chrome.google.com/webstore/detail/checkchrome/bgjhmmigallkdooefglpgfamapoconfo?hl=en-US
Click to Remove Element
https://chrome.google.com/webstore/detail/click-to-remove-element/jcgpghgjhhahcefnfpbncdmhhddedhnk
Mercury Reader
https://chrome.google.com/webstore/detail/mercury-reader/oknpjjbmpnndlpmnhmekjpocelpnlfdi


http://stackoverflow.com/questions/37487784/sending-request-from-https-to-http-from-chrome-extension

https://developer.chrome.com/extensions/getstarted
https://github.com/altryne/extensionizr
https://developer.chrome.com/extensions/overview

Many extensions have a background page, an invisible page that holds the main logic of the extension. An extension can also contain other pages that present the extension's UI. If an extension needs to interact with web pages that the user loads (as opposed to pages that are included in the extension), then the extension must use a content script.
Background pages defined by background.html can include JavaScript code that controls the behavior of the extension. There are two types of background pages: persistent background pages, and event pages. Persistent background pages, as the name suggests, are always open. Event pages are opened and closed as needed. Unless you absolutely need your background page to run all the time, prefer to use an event page.
If your extension needs to interact with web pages, then it needs a content script. A content script is some JavaScript that executes in the context of a page that's been loaded into the browser. Think of a content script as part of that loaded page, not as part of the extension it was packaged with (its parent extension).
Content scripts can read details of the web pages the browser visits, and they can make changes to the pages. In the following figure, the content script can read and modify the DOM for the displayed web page. It cannot, however, modify the DOM of its parent extension's background page.
A browser window with a browser action (controlled by background.html) and a content script (controlled by contentscript.js).
Content scripts aren't completely cut off from their parent extensions. A content script can exchange messages with its parent extension, as the arrows in the following figure show. For example, a content script might send a message whenever it finds an RSS feed in a browser page. Or a background page might send a message asking a content script to change the appearance of its browser page.
https://developer.chrome.com/extensions/event_pages

https://developer.chrome.com/extensions/messaging
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
    console.log(response.farewell);
  });
});
On the receiving end, you need to set up an runtime.onMessage event listener to handle the message. This looks the same from a content script or extension page.
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 Extension - Context Menu On Specific Pages
http://stackoverflow.com/questions/20863005/chrome-extension-context-menu-on-specific-pages
var showForPages = ["https://www.google.com/","*://github.com/zambrey/*","http://www.nytimes.com/"];

chrome.contextMenus.create({
    "title": "zambrey",
    "documentUrlPatterns":showForPages
});
Be sure to check out http://developer.chrome.com/extensions/match_patterns.html for more details on url pattern syntax.
http://stackoverflow.com/questions/14452777/is-that-possible-calling-content-script-method-by-context-menu-item-in-chrome-ex
    "background": {
        "scripts": [
            "background.js"
        ]
    },
    "content_scripts": [
        {
            "matches": [
                "<all_urls>"
            ],
            "js": [
                "myscript.js"
            ]
        }
    ],
    "permissions": [
        "contextMenus"
    ]

background.js

function genericOnClick(info, tab) {
    console.log("item " + info.menuItemId + " was clicked");
    console.log("info: " + JSON.stringify(info));
    console.log("tab: " + JSON.stringify(tab));

    //Add all you functional Logic here
    chrome.tabs.query({
        "active": true,
        "currentWindow": true
    }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {
            "functiontoInvoke": "showInfo"
        });
    });
}

    var id = chrome.contextMenus.create({
        "title": title,
        "contexts": [context],
        "onclick": genericOnClick
    });



myscript.js


var showInfo = function () {
    console.log("Show Info is invoked");
}
var showAnotherInfo = function () {
    console.log("Show Another Info");
}
chrome.extension.onMessage.addListener(function (message, sender, callback) {
    if (message.functiontoInvoke == "showInfo") {
        showInfo();
    }
    if (message.functiontoInvoke == "showAnotherInfo") {
        showAnotherInfo();
    }
});

Is there any particular reason you use chrome.tabs.query(...) instead of just doingchrome.tabs.sendMessage(tab.id, ...)?

http://stackoverflow.com/questions/23593588/the-difference-between-the-code-in-background-script-and-content-script
In short, content scripts execute in an isolated context of a webpage, having access to its DOM, but have very limited Chrome API access.
A background script is usually used for central handling of tasks, while content scripts act as intermediaries between it and pages you want to interact with.
You need to have a background script to listen to the button click event.
You need to have a content script to interact with a page.
So, you need both, and the background script can message the content script to do its magic.

Chrome Extensions have two "modes" when making cross-domain XHR requests:
1) If the domain is in the "permissions" section of the manifest.json file - The request doesn't have an "Origin" header, and it always succeeds.
2) If the domain is not in "permissions" - The request includes an "Origin" header with the value "chrome-extension://..." This indicates that the request is a CORS request, and the response must have a valid Access-Control-Allow-Origin header in order to succeed.
https://developer.chrome.com/extensions/match_patterns
file:///foo*Matches any local file whose path starts with /foofile:///foo/bar.html
file:///foo
http://127.0.0.1/*Matches any URL that uses the http scheme and is on the host 127.0.0.1http://127.0.0.1/
http://127.0.0.1/foo/bar.html

Labels

Review (572) System Design (334) System Design - Review (198) Java (189) Coding (75) Interview-System Design (65) Interview (63) Book Notes (59) Coding - Review (59) to-do (45) Linux (43) Knowledge (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (31) Big Data (29) Product Architecture (28) MultiThread (27) Soft Skills (27) Concurrency (26) Cracking Code Interview (26) Miscs (25) Distributed (24) OOD Design (24) Google (23) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) System Design - Practice (20) Tips (19) Algorithm (17) Company - Facebook (17) Security (17) How to Ace Interview (16) Brain Teaser (14) Linux - Shell (14) Redis (14) Testing (14) Tools (14) Code Quality (13) Search (13) Spark (13) Spring (13) Company - LinkedIn (12) How to (12) Interview-Database (12) Interview-Operating System (12) Solr (12) Architecture Principles (11) Resource (10) Amazon (9) Cache (9) Git (9) Interview - MultiThread (9) Scalability (9) Trouble Shooting (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Cassandra (8) Company - Uber (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Design (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Mac (7) Machine Learning (7) NoSQL (7) C++ (6) Chrome (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) Python (5)

Popular Posts