Tags

, , , , , , , ,

This is an extension to my earlier post on creating chrome app,
Ref : https://johngcek.wordpress.com/2013/03/30/creating-a-chrome-app/

In this will be looking into a bit more powerful app building.

As explained earlier, we need to have a manifest.json, and a couple of html pages to get our app working. Here we will create an app, which can call a php page from server and get the results..

manifest.json:
{
“name”: “PHP Value Fetcher”,
“version”: “0.1”,

“description”: “Sample to get the PHP values from server”,
“icons”: { “16” : “images/icon.png”,
“48” : “images/icon48.png”,
“128” : “images/icon128.png”},
“homepage_url”: “http://localhost/test/”,
“background_page”: “background.html”,
“permissions”: [
http://localhost/test/*”
],
“browser_action”: {
“default_icon”: “images/icon.png”,
“default_title”: “PHP Value Fetcher”,
“default_popup”: “popup.html”
}
}

Here the background page is the one that we run on the background which gets us the required data. One thing that need to be noted is the permissions section. The app will not return any values if the permission is not configured properly, there wont be any error messages too.

For this project, I have set the homepage as my local testing location, localhost, in the doc root I have a folder name “test”. I am calling PHP file, from within this folder. So I need to set permission as “localhost/test/*”.

popup.html:
<html>
<head>
<script src=’scripts/jquery-1.6.1.min.js’></script>
<script>
function fetch_feed() {
chrome.extension.sendRequest({‘action’ : ‘fetch_feed’,
‘url’ : ‘http://localhost/test/forChrome.php&#8217;},
function(response) {
display_stories(response);
}
);
}

function display_stories(feed_data) {
$(‘#popup’).html(feed_data);
//$(‘#popup’).append(‘<img src=”images/logo.png” id=”logo” onclick=”open_item(\’http://localhost/test/\’); window.close();” /><br clear=”all” />’);
}

</script>
<link rel=”stylesheet” href=”styles/post.css” type=”text/css” />
</head>
<body>
<div id=”popup”>
</div>
<script>
$(document).ready(function() {
fetch_feed();
});
</script>
</body>
</html>

background.html:
<html>
<head>
<script src=’scripts/jquery-1.6.1.min.js’></script>
<script>
function fetch_feed(url, callback) {
var xhr = new XMLHttpRequest();  // Initiates the ajax call to the php file passed from popup.html
xhr.onreadystatechange = function(data) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var data = xhr.responseText;
callback(data);
} else {
callback(null);
}
}
}
xhr.open(‘GET’, url’, true); // Note: this url should be set in permission section
//xhr.open(‘GET’, url+’?user=john’, true); If you need to pass arguments
xhr.send();
}

function onRequest(request, sender, callback) {
if (request.action == ‘fetch_feed’) {
fetch_feed(request.url, callback);
}
}
chrome.extension.onRequest.addListener(onRequest);
</script>
</head>
<body>
</body>
</html>

Advertisements