mylamour/blog

How about write a chrome extension?

Opened this issue · 0 comments

image
As you know, chrome is one of the most popular browsers, And it have many features. So it's worth to write a chrome extensions for yourself to improve working efficiency .
Firstly, let's us look at the folder structure.
image
with above picature, all you should concerned was about two point.

  1. folder structure
  • mainfest.json
  • popup.html
  • popup.js
  1. api
  • chrome api

In fact, when i try to learn how to write a chrome extension, i got some problem with load script.
It's prioritized, you should put all scripts which you want on mainfest.json and in speical field.
The mainfest.json file was contained lot of field with value.

{
	"manifest_version": 2,
	"name": "SaveM",
	"version": "0.01",
	"description": "Simple to save as pdf",
	"author": "mour",
	"icons":
	{
		"48": "icon.png",
		"128": "icon.png"
	},
	"browser_action": 
	{
		"default_icon": "icon.png",
		"default_popup": "popup.html"
	},
	"background": {
		"scripts": ["js/background.js"]
	},
	"content_scripts": 
	[
		{
			"matches": ["<all_urls>"],
			"js": ["js/jquery-3.4.0.min.js","js/jspdf.min.js","js/popup.js","js/content-script.js"],
			"run_at": "document_start"
		}
	],
	"permissions":
	[
		"contextMenus", 
		"activeTab",
		"tabs", 
		"clipboardWrite",
		"notifications",
		"webRequest",
		"webRequestBlocking", 
		"storage", 
		"http://*/*", 
		"https://*/*" 
	],
	"web_accessible_resources": 
	[
		"js/inject.js"
	]
	
}

In the code snippet above, we can see some feild like background,content_script,web_accessible_resources, As the name indicates, background allowed your code running on the entired lifecycle, not only in the special tab, and content_scripts was only run in webpage. Also, even if you can execute the script, but you still should to apply permissions which your extension was being needed, or you can't do anything.

popup.html is the main display of your extension, it was consisted of html simply, In this file, you can definite your style to suitable your preference.

<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8" />
	<title>Save</title>
	<link rel="stylesheet" href="./css/materialize.min.css">

	<script type="text/javascript" src="js/jspdf.min.js"></script>
	<script type="text/javascript" src="js/jquery-3.4.0.min.js"></script>
</head>

<body style="height: 20px; width: 100px;">
	<div class="container">
		<a href="#" id="save" class="btn-small btn-flat">
			<i class="material-icons left">Save
			</i>
		</a>
	</div>

	<script type="text/javascript" src="js/popup.js"></script>
</body>

</html>

image

Now, you can see it on your brower like this above. but you can't do anything with it, because the action of click was not defined. then you need to define it. so we can defined our action in popup.html with script tag, in this example, we use popup.js.

function getCurrentTabId(callback) {
	chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
		if (callback) callback(tabs.length ? tabs[0].id : null);
	});
}

function executeScriptToCurrentTab(code) {
	getCurrentTabId((tabId) => {
		chrome.tabs.executeScript(tabId, { code: code });
	});
}

$('#read').click(() => {
	getCurrentTabId((tabId) => {
		chrome.tabs.executeScript(tabId, { file: './js/clean.js' });
	});
});

you can find which is important, if you want to do something intracitve with dom, you need to execute script in special tab, or current tab. with chrome.tabs.executeScript and chrom.executeScriptToCurrentTab . chrome.tabs.executeScript has parameters, one of them is type.

chrome.tabs.executeScript(tabId, { file: './js/clean.js' });
chrome.tabs.executeScript(tabId, { code: 'alert(1)' });

And in this example, i try to use clean.js to clean the page(remvoe the redundant text or style, only save the main of page). clean.js should be easily write in common sitution.

$(function clean() {

    var config = {
        "www.baidu.com": [
            'alert(1)',
        ],
        "xxxxxxx.com": [
            // lazy....
            `
            $("body > div:nth-child(5) > div > div > article > div.content.unsafe.md").removeAttr("style");
            var save = $("body > div:nth-child(5) > div");
            $('body').empty();
            $('body').html(save);
        
            $("body > div > div > div.no-padding").empty();
            $("body > div > div > article > header").empty();
            $("body > div._article-container > div > ul > li > a").empty();
            $("body > div._article-container > div > section").empty();
            $("#voters").empty();
            $("body > div > div > article > div._article-float.hidden-xs > div > div > aside").empty();
            $("body > div > div > article > footer").empty();
            $("#article-recommend").empty();
            `
        ],
        "www.jianshu.com": [
            `
            var header = $("head");
            var save = $("body > div.note > div.post > div.article");
            $('body').empty();
            $('body').html(header);
            $('body').html(save);
            `
        ]
    }

    if (config.hasOwnProperty(window.location.host) != -1) {
        config[window.location.host].forEach(function (c) {
            eval(c);
        });
    }

});

Now, you can do whatever you want with your extension. if you want to know about api deeply, you can find some document was useful in this below.

for chinese:

for english:

And most important is In unity of knowing and doing, github is good place and have lot examples. good luck.