LoginSignup
11
10

More than 5 years have passed since last update.

ChromeExtension(BrowerAction)で、AjaxでJSONをやりとりする簡単なサンプル

Last updated at Posted at 2014-09-30

概要

  • BrowserActionのアイコンをクリックすると、Ajaxでサーバ(PHP)と通信する。
  • サーバから数値がJSONで返答され、その結果をBrowserActionのボタンに表示する
  • ポップアップ画面は表示しない

browseraction1.png

クリックすると、サーバから数値がJSONで返答され、ボタンに表示される↓

browseraction2.png

コード

manifest.json
{
    "name": "Ajax Sample",
    "version": "0.1",
    "manifest_version": 2,
    "description": "Ajax Sample",
    "permissions": ["http://sample.info/*"], 
    "browser_action": {
        "default_title": "Ajax Sample"
    },
    "background": {
    "scripts": ["background.js"]
    }
}

background.js
chrome.browserAction.onClicked.addListener(function(tab){
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4 && xhr.status == 200){
            chrome.browserAction.setBadgeText({text:""+JSON.parse(xhr.responseText).num});
        }
    }
    var url = 'http://sample.info/ajax.php';
    xhr.open('GET', url, true);
    xhr.send();
});
ajax.php
<?php

echo json_encode(array('num' => 1));
11
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10