Chrome Extension hands-on operations

Source: Internet
Author: User

There are two main reasons for wanting to play chrome plug-ins recently. One is that some time ago I was not satisfied with the functionality of chrome new tab, and the existing plug-ins could not meet the requirements. because the interface design is really my obstacle and my own needs are not urgent, I did not do it. The other is recently I want to find an ipad mini on the company's intranet, it is often booked within half an hour of sales. Therefore, we want to use chrome's desktop reminder function to provide a real-time reminder plug-in. the function is simple, as shown in the following code:

  1. Request the first few pages of the Forum every x seconds to find all new posts marked with "new"
  2. Based on the post title, match the keyword "pad mini" I need for display
  3. Desktop reminder: The post owner, title, and address should be clickable and can be clicked directly.
  4. Remove duplicates. Do not remind me of posts that have already been reminded.

I read the extension document a little during newtab:

Https://developer.chrome.com/extensions/docs.html

Many websites in the company are not accessible, but https is still used and occasionally hard to generate. Later, we found many images, such:

Https://sites.google.com/site/crxdoczh/reference/api_index/extension

The information is not up-to-date, but it is basically enough.

Browse "Getting Started" and get Started.

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

1. Write manifest. json,

{    "name": "Iwant",    "version": "1.0",    "manifest_version": 2,    "background" : {        "persistent": false,        "scripts": ["jquery-1.8.3.min.js", "iwant.js"]    },    "permissions": [      "notifications",      "storage",      "cookies"    ],    "content_security_policy": "script-src 'self'; object-src 'self'"}

This is not difficult. Just copy it. Pay attention to the following points:

  1. Strictly follow the JSON format. For example, a comma is not allowed at the end.
  2. I used local js, so I need to add the content_security_policy policy.
  3. Apply for sufficient permissions
  4. There is no UI, and you want the plug-in to be loaded or executed when chrome is started. Check "backgroud"

It's almost done. Download jquery and create an empty iwant. js file to debug it.

------------------------------------------------------------------------------

Ii. debugging

Open the chrome plug-in page chrome: // extensions/, check the developer mode, and load the application according to the "Getting Started" instructions.

Pay attention to the Inspect views connection of the plug-in. Click it to open a new console, which contains the permissions specified by manifest. json and allows debugging at will.

------------------------------------------------------------------------------

Iii. Commencement

 1 g_IWant = 'mini'; 2 g_wants = []; 3  4 function _removeOutdated(shownurls){ 5     var now = new Date; 6     for (url in shownurls){ 7         if (now - shownurls[url] > 86400000){ 8             delete shownurls[url]; 9         }10     }11 }12 13 function showWant(name, title, url){14     if (title.indexOf(g_IWant) == -1){15         return;16     }17     chrome.storage.local.get('shownurl', function(items){18         if (!items.shownurl){19             items.shownurl = {};20         }21         var shownurl = items.shownurl;22         if (!shownurl[url]){23             _removeOutdated(shownurl);24             var want = {name:name, title:title, url:url};25             if (g_wants.length > 10){26                 g_wants.shift();27             }28             g_wants.push(want);29             shownurl[url] = new Date;30             chrome.storage.local.set(items);31         }32     })33 }34 35 function findWant(pages){36     if (pages <= 0){37         return;38     }39     var xhr = new XMLHttpRequest();40     xhr.open('GET', 'http://bbs.com/forum?page='+pages, true);41     xhr.onreadystatechange = function(){42         if (xhr.readyState == 4){43             var html = xhr.responseText;44             var body = html.substring(html.search('<body>'), html.search('</body>')+8);45             $('#content table tr', $(body)).has('td img[src="http://bbs.com/img/new.gif"]').each(function(i, item){46                 var $item = $(item);47                 var url = $item.find('td:first a[href][title]').attr('href');48                 var title = $item.find('td:first a[href][title]').text();49                 var name = $item.find('td:eq(1)').text();50                 showWant(name, title, url);51             })52             findWant(pages-1);53         }54     }55     xhr.send();56 }57 58 function showWantToNotification(){59     var want = g_wants.shift();60     if (!want) return;61     var query = 'name='+encodeURI(want.name)+'&title='+encodeURI(want.title)+'&url='+encodeURI('http://bbs.com'+want.url);62     var tip = webkitNotifications.createHTMLNotification('notify.html?'+query);63     tip.replaceId = 'wanted';64     tip.show();65 }66 67 68 setInterval(function(){findWant(2);}, 5000);69 setInterval(function(){showWantToNotification();}, 5000);

 

  1. Two timers, one crawling page and one desktop notification, ensure that each display lasts for 5 seconds;
  2. The findWant function provides the pages parameter to specify the first few pages to be crawled. Based on the actual situation, there are usually new posts on the first two pages.
  3. ShowWant inserts a suitable post into the global list, and then displays the notification in another timer.

In this case, desktop notification only supports two formats: plaintext or url. you can click here. plaintext is definitely not usable. you can no longer set up a server to receive data to transmit data. after half a day, we had to use the local js file to break down the GET parameter for data transmission. for example, policy.html specified in showwanttonotification

<!DOCTYPE html>

And notify. js

var url = window.location.href;var query = url.split('?')[1];var params = {};if (query){    var names = query.split('&');    names.forEach(function(param){        var tuple = param.split('=');        var key = tuple[0], value = decodeURI(tuple[1]);        params[key] = value;    })}if (params['name'] && params['title'] && params ['url']){    var html = '';    html += '<div>' + params['name'] + '</div>';    html += '<div><a target="_blank" href="'+params['url']+'">'+params['title']+'</a></div>';    document.getElementById('iw_content').innerHTML = html;}

-----------------------------------------------

4. debug and launch

The code is almost written, and debugging is required.

You can directly reload the Extensions page and monitor the data on the console. This is simple and has two problems:

1. resumicaion debugging occurs after it is created ..

2. The mouse over the hyperlink in javasicaion under my system is not pointer...

After debugging, You can package it on the Extensions page. Then, you can use it for your colleagues.

 

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

In general, extension development in chrome is relatively simple and interesting. The documentation is relatively complete and there are not many pitfalls. It takes care of me as a rookie hacker who is not familiar with JS.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.