トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS

JavaScript:ChromeExtension:アイコンをクリックしたら新しいタブを開きたい のバックアップソース(No.1)

[[JavaScript:GoogleChromeのExtensionでJavaScriptを勉強する]]

*JavaScript:GoogleChrome:アイコンをクリックしたら新しいタブを開きたい [#b325731d]

ChromeのExtensionのアイコンを開いたら、新しいタブでExtensionのコンテンツを表示したかったです。

一見manifest.jsonに記述するだけでいけそうな気がしていたのですが、なんか無理っぽいので、backgroundページのjsで何とかする方法をとりました。

いちよう、ここを見ました
■Formats: Manifest Files
-http://developer.chrome.com/extensions/manifest.html

***実際のソース [#d2a08869]

ファイルはソース3つ+アイコンです。

-manifest.json
-background.js
-top.html

■manifest.json
 {
   "manifest_version": 2,
 
   "name": "ChromeExtensionNewTabTest",
   "description": "ChromeExtensionNewTabTest",
   "version": "1.0",
 
   "permissions": [
     "tabs"
   ],
 
   "background": {
     "scripts": ["background.js"]
   },
 
   "browser_action": {
     "default_icon": "icon.png"
   }
 }

■background.js
 chrome.browserAction.onClicked.addListener(function() {
   chrome.tabs.create({url: "top.html"});
 });

■top.html
 <!doctype html>
 <html>
   <head>
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
     <title>アイコンをクリックしたらタブが開くChrome Extensionサンプル</title>
     <style>
       h1,h2 { color:blue; font-style:italic }
       
       .IMPORTANT{
         font-weight: bold;
         font-size: 150%;
         margin: 0 1in 0 1in;
         background-color: yellow;
         border: solid red 8px;
         padding: 10px;
       }
       
       .IMPORTANT h1, .IMPORTANT h2 { text-align; center }
       
       #special {
         text-align: center;
         text-transform: uppercase;
       }
       
     </style>
 
   </head>
   <body>
     <h1>アイコンをクリックしたらタブが開くChrome Extensionサンプル</h1>
     <div class="IMPORTANT">
       <h2>重要</h2>
       これはアイコンをクリックしたらタブが開くChromeExtensionのサンプルです。
       CSS、JavaScriptの勉強がてら作ってます。
     </div>
     <p id="special">
       このエリアは小文字を大文字に変換して出力します。<br />
       Lower-case letters are transformed upper-case letters in this area.
     </p>
   </body>
 </html>

***ポイント [#yca53d06]

ポイントは以下の通り。

-manifest.jsでbackgroundページのスクリプトとして、「background.js」をロードする
-background.jsの中で、アイコンがクリックされた場合のイベント処理として、「chrome.tabs.create」で新しいタブを開く


■APIリファレンス:browserAction
-https://developer.chrome.com/extensions/browserAction.html#event-onClicked
■APIリファレンス:tabs
-https://developer.chrome.com/extensions/tabs.html#method-create