前回はChrome拡張機能とローカルプログラムの連携までを書きました。
今回はその続きです。
URLの監視
特定のURLにアクセスした場合にメッセージを表示するため
URLの監視を行います。
監視を行うには
manifest.jsonのcontent_scriptsの項目にあるjsで行います。
今回ですと「message.js」です。
message.js
/*
■ URL監視
*/$(function(){try{// background.jsにurlを送るchrome.runtime.sendMessage({method:'checkurl',url:document.URL},errorHandle(function(response1){// 必要ないけどとりあえず受け取るvarmessage=response1.data;}));}catch(e){console.error(e);}});/**
* 例外をまとめて処理する
*/functionerrorHandle(process){returnfunction(){try{returnprocess.apply(this,arguments);}catch(e){chrome.browserAction.setIcon({path:"images/abnormal.png"});console.error(e);}};}message.jsから受け取るためbackground.jsを以下の内容に修正しています。
background.js
/*
初期起動時の処理
*/// インストール時かバージョンアップ時chrome.runtime.onInstalled.addListener(function(){initialize();});// ブラウザ起動時chrome.runtime.onStartup.addListener(function(){initialize();});functioninitialize(){// ファイルダウンロード先vardlFileName="http://localhost/sample.txt";// ファイルを取得$.ajax({url:dlFileName,type:"GET",dataType:'binary',responseType:'arraybuffer',timeout:500})// 成功時.done(errorHandle(function(response){vardata=response;// ArrayBufferで取得するのでvartextfiledata=String.fromCharCode(...newUint8Array(data));console.log(textfiledata);// 渡す前にbase64エンコードしておくtextfiledata=btoa(textfiledata);// ダウンロードした内容をprogramに連携するchrome.runtime.sendNativeMessage('put.message',{Action:"putmessage",Data:textfiledata},errorHandle(function(response,thread){// デコードしてJSON形式にするvargetData=JSON.parse(decodeURIComponent(response));// 受け取ったコードがエラーの場合if(getData.Code!=0){thrownewError('programでエラーが発生');}// 受け取ったデータをlocalStorageに保存しておくlocalStorage.setItem('urllist',atob(getData.Data));returntrue;}));// 成功した場合は拡張機能のアイコンを切り替えるchrome.browserAction.setIcon({path:"images/success.png"});// localStorageにステータスを保存localStorage.setItem('Status','ok');}))// 失敗時.fail(errorHandle(function(){// localStorageにステータスを保存localStorage.setItem('Status','ng');}));returntrue;}/**
* Chrome拡張全体用
*/chrome.runtime.onMessage.addListener(function(request,sender,sendResponse){switch(request.method){// マニフェストファイルの内容を取得するcase'getManifest':varmanifest=chrome.runtime.getManifest()sendResponse({data:manifest})break;// URLを受け取るcase'checkurl':varurl=request.url;// urllistの内容と一致するか確認するlocalStorage.setItem('match','URLが一致しません。');varurllist=JSON.parse(localStorage.getItem('urllist'));for(varkeyofObject.keys(urllist)){if(url==urllist[key]){// 含んでいる場合localStorage.setItem('match','URLが一致します。');sendResponse({data:"URLが一致します。"});break;}}break;case'getApInfo':default:console.log('no method:'+request.method);break;}returntrue;});/**
* 例外をまとめて処理する
*/functionerrorHandle(process){returnfunction(){try{returnprocess.apply(this,arguments);}catch(e){chrome.browserAction.setIcon({path:"images/abnormal.png"});console.error(e);}};}あとはメッセージを表示するためpopup系を修正します。
popup.html
<!DOCTYPE html><htmllang="ja"><head><metahttp-equiv="Content-Type"content="text/html; charset=utf-8"/><metahttp-equiv="Pragma"content="no-cache"><metahttp-equiv="Cache-Control"content="no-cache"><linkhref="../css/popup.css"rel="stylesheet"><script src="../js/jquery-3.4.1.js"></script><script src="../js/popup.js"></script></head><bodyid="body"><divclass="box"><divclass="header"><h3style="margin: 5px 0">動作状況</h3></div><div><pid="status"></p></div><div><pid="match"></p></div></div><divclass="footer"><divid="productver"></div></div></body></html>popup.js
$(function(){/*** localStorageからステータスを取得。 ***/varStatus=localStorage.getItem('Status');varmatch=localStorage.getItem('match');if(Status=='ok'){$('#status').html('<b>正常</b>');$('#match').html(match);}else{$('#status').html('<b>異常</b>');}// 特に意味はないけどマニフェストファイルのバージョン情報を取得するchrome.runtime.sendMessage({method:'getManifest'},function(response){varmanifest=response.data;$('#productver').text(manifest.name+' ver.'+manifest.version);});});拡張機能の作成については以上になります。
次回はChrome拡張機能のインストールについて投稿します。