EDITED
I have a code to show a html in wxPython WebView but it just load the html without the css and javascript inside the html file. Here is my code.
gui.py
class MainFrame(wx.Frame):
def __init__( self, parent ):
wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = u"PlagDetect", pos = wx.DefaultPosition, size = wx.Size( 493,389 ),
self.htmlSummary = wx.html2.WebView.New(self)
page = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Summary</title>
</head>
<body>
<h1>Summary</h1>
<div id="piechart"></div>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load google charts
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
// Draw the chart and set the chart values
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 8],
['Eat', 2],
['TV', 4],
['Gym', 2],
['Sleep', 8]
]);
// Optional; add a title and set the width and height of the chart
var options = {'title':'My Average Day', 'width':550, 'height':400};
// Display the chart inside the <div> element with id="piechart"
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</body>
</html>
"""
summary.htmlSummary.SetPage(page, "")
I've found the answer to create Pie Chart in other way with PieCtrl instead of using WebView, thanks to mr #Rolf of Saxony . The answer is written below.
In answer to your comment, "is there any other way to create a pie chart in wxpython", yes, see: https://wxpython.org/Phoenix/docs/html/wx.lib.agw.piectrl.PieCtrl.html
At it's simplest:
import wx
import wx.lib.agw.piectrl
from wx.lib.agw.piectrl import PieCtrl, PiePart
class Frame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__ (self, parent, -1, "Simple Pie Chart")
panel = wx.Panel(self, -1, size=(650,650))
# Create A Simple PieCtrl With 3 Sectors
self._pie = PieCtrl(panel, -1, wx.DefaultPosition, wx.Size(180,270))
self._pie.GetLegend().SetTransparent(True)
self._pie.GetLegend().SetHorizontalBorder(10)
self._pie.GetLegend().SetWindowStyle(wx.STATIC_BORDER)
self._pie.GetLegend().SetLabelFont(wx.Font(10, wx.FONTFAMILY_DEFAULT,
wx.FONTSTYLE_NORMAL,
wx.FONTWEIGHT_NORMAL,
False, "Courier New"))
self._pie.GetLegend().SetLabelColour(wx.Colour(0, 0, 127))
self._pie.SetHeight(10)
self._pie.SetAngle(0.35)
part = PiePart()
part.SetLabel("Label_1")
part.SetValue(300)
part.SetColour(wx.Colour(200, 50, 50))
self._pie._series.append(part)
part = PiePart()
part.SetLabel("Label 2")
part.SetValue(200)
part.SetColour(wx.Colour(50, 200, 50))
self._pie._series.append(part)
part = PiePart()
part.SetLabel("Label 3")
part.SetValue(50)
part.SetColour(wx.Colour(50, 50, 200))
self._pie._series.append(part)
self.Show()
app = wx.App()
frame = Frame(None)
app.MainLoop()
After a tiny clean up of your posted code, it appears to work well. Although, I don't see any css, the javascript section works
Note: I run on Linux
import wx
import wx.html2
class MainFrame(wx.Frame):
def __init__( self, parent ):
wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = u"PlagDetect", pos = wx.DefaultPosition, size = wx.Size( 600,450 ))
self.htmlSummary = wx.html2.WebView.New(self)
page = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Summary</title>
</head>
<body>
<h1>Summary</h1>
<div id="piechart"></div>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load google charts
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
// Draw the chart and set the chart values
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 8],
['Eat', 2],
['TV', 4],
['Gym', 2],
['Sleep', 8]
]);
// Optional; add a title and set the width and height of the chart
var options = {'title':'My Average Day', 'width':550, 'height':400};
// Display the chart inside the <div> element with id="piechart"
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</body>
</html>
"""
self.htmlSummary.SetPage(page, "")
if __name__ == "__main__":
app = wx.App()
frame_1 = MainFrame(None)
frame_1.Show()
app.MainLoop()
Related
I'm trying to draw a Google Line Chart but I've some problem drawing the second line. I'm using data from my MySQL database which allow me to display the sum amount of sold pieces grouped by months in 2018.
But I'd like to display the sum amount divided for every responsibility group which is a string value inside my every row.
This is my code:
<?php
$curyear = date('Y');
$con = mysqli_connect('xxxx','xxxx','xxxx','xxxx');
?>
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = google.visualization.arrayToDataTable([
['Date', 'Pezzi',],
<?php
$query = "SELECT responsabile, sum(n_sim)+sum(n_accessi) as pezzi, data_dichiarato FROM dichiarati WHERE responsabile = 'ADMRZ01' and n_ragsoc != 'DICHIARATO ZERO' and YEAR(DATA_DICHIARATO) = '$curyear' GROUP BY MONTH(data_dichiarato) ORDER BY data_dichiarato";
$exec = mysqli_query($con,$query);
while($row = mysqli_fetch_array($exec)){
echo "['".date("M", strtotime($row['data_dichiarato']))."',".$row['pezzi']."],";
}
?>
]);
// Set chart options
var options = {'title':'SIM CONSEGNATE NEL <?php echo $curyear; ?>',
'width':1200,
'height':300
// isStacked: true
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Divs that will hold the charts-->
<div id="chart_div"></div>
</body>
</html>
So as you can see I have a single query which extracts data just for responsibility ADMRZ01. But in my database, I've rows with ADMRZ02, ADMRZ11, and others.
I'd like to have a line in Linechart for every responsibility I'm adding.
How can I modify my code?
Is it necessary to add another query? Or a Series?
I'm sorry I'm just a beginner in charts
Thanks
in order to have multiple lines / series,
the google data table will need to look something like the following...
var data = google.visualization.arrayToDataTable([
['Date', 'ADMRZ01', 'ADMRZ02', 'ADMRZ11'],
['Jan', 10, 20, 30],
...
]);
but this would very difficult to build from the query, without a bunch of hard-coding
instead, add a column for responsibility,
then we can use google data methods to transform the rows to columns.
to begin, the data table will look something like...
var data = google.visualization.arrayToDataTable([
['Date', 'Responsibility', 'Pezzi'],
['01/01/2018', 'ADMRZ01', 10],
['01/01/2018', 'ADMRZ02', 20],
['01/01/2018', 'ADMRZ11', 30],
['02/01/2018', 'ADMRZ01', 40],
['02/01/2018', 'ADMRZ02', 50],
['02/01/2018', 'ADMRZ11', 60],
['03/01/2018', 'ADMRZ01', 70],
['03/01/2018', 'ADMRZ02', 80],
['03/01/2018', 'ADMRZ11', 90],
]);
you'll want to keep the dates, because when we aggregate,
the month names will get sorted alphabetically, and will be out of order.
e.g. --> Apr, Aug, Dec, Feb, etc...
we can format as month name later.
first, change the query to include all responsibilities...
var data = google.visualization.arrayToDataTable([
['Date', 'Responsabile', 'Pezzi'],
<?php
$query = "SELECT data_dichiarato, responsabile, sum(n_sim)+sum(n_accessi) as pezzi FROM dichiarati WHERE n_ragsoc != 'DICHIARATO ZERO' and YEAR(DATA_DICHIARATO) = '$curyear' GROUP BY data_dichiarato, responsabile ORDER BY data_dichiarato";
$exec = mysqli_query($con,$query);
while($row = mysqli_fetch_array($exec)){
echo "['".$row['data_dichiarato']."','".$row['responsabile']."'".$row['pezzi']."],";
}
?>
]);
then you can use the following javascript to transform the rows to columns,
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
// create data table
var data = google.visualization.arrayToDataTable([
['Date', 'Responsibility', 'Pezzi'],
['01/01/2018', 'ADMRZ01', 10],
['01/01/2018', 'ADMRZ02', 20],
['01/01/2018', 'ADMRZ11', 30],
['02/01/2018', 'ADMRZ01', 40],
['02/01/2018', 'ADMRZ02', 50],
['02/01/2018', 'ADMRZ11', 60],
['03/01/2018', 'ADMRZ01', 70],
['03/01/2018', 'ADMRZ02', 80],
['03/01/2018', 'ADMRZ11', 90],
]);
// create data view
var view = new google.visualization.DataView(data);
// column arrays
var aggColumns = [];
var viewColumns = [{
// convert string to date
calc: function (dt, row) {
return new Date(dt.getValue(row, 0));
},
label: data.getColumnLabel(0),
type: 'date'
}];
// build view & agg columns for each responsibility
data.getDistinctValues(1).forEach(function (responsibility, index) {
viewColumns.push({
calc: function (dt, row) {
if (dt.getValue(row, 1) === responsibility) {
return dt.getValue(row, 2);
}
return null;
},
label: responsibility,
type: 'number'
});
aggColumns.push({
aggregation: google.visualization.data.sum,
column: index + 1,
label: responsibility,
type: 'number'
});
});
// set view columns
view.setColumns(viewColumns);
// sum view by date
var aggData = google.visualization.data.group(
view,
[0],
aggColumns
);
// draw chart
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(aggData, {
title: 'SIM CONSEGNATE NEL...',
hAxis: {
format: 'MMM',
ticks: view.getDistinctValues(0)
}
});
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
note: jsapi should no longer be used to load the charts library,
according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. The last update, for security purposes, was with a pre-release of v45. Please use the new gstatic loader.js from now on.
this will only change the load statement, see above snippet...
<?php
$curyear = date('Y');
$con = mysqli_connect('localhost','root','root','tetra');
?>
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
var data1 = google.visualization.arrayToDataTable([
['Date', 'Pezzi01'],
<?php
$query = "SELECT responsabile, sum(n_sim)+sum(n_accessi) as pezzi01, data_dichiarato FROM dichiarati WHERE responsabile = 'ADMRZ01' and n_ragsoc != 'DICHIARATO ZERO' and YEAR(DATA_DICHIARATO) = '$curyear' GROUP BY MONTH(data_dichiarato), responsabile order by data_dichiarato asc";
$exec = mysqli_query($con,$query);
while($row = mysqli_fetch_array($exec)){
echo "['".date("M", strtotime($row['data_dichiarato']))."',".$row['pezzi01']."],";
}
?>
]);
var data2 = google.visualization.arrayToDataTable([
['Date', 'Pezzi02'],
<?php
$query = "SELECT responsabile, sum(n_sim)+sum(n_accessi) as pezzi02, data_dichiarato FROM dichiarati WHERE responsabile = 'ADMRZ02' and n_ragsoc != 'DICHIARATO ZERO' and YEAR(DATA_DICHIARATO) = '$curyear' GROUP BY MONTH(data_dichiarato), responsabile order by data_dichiarato asc";
$exec = mysqli_query($con,$query);
while($row = mysqli_fetch_array($exec)){
echo "['".date("M", strtotime($row['data_dichiarato']))."',".$row['pezzi02']."],";
}
?>
]);
var joinedData = google.visualization.data.join(data1, data2, 'full', [[0, 0]], [1], [1]);
var chart = new google.visualization.LineChart(document.querySelector('#chart_div'));
chart.draw(joinedData, {
height: 300,
width: 600,
interpolateNulls: true,
});
}
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});
</script>
</head>
<body>
<!--Divs that will hold the charts-->
<div id="chart_div"></div>
</body>
</html>
Found another solution with method google.visualization.data.join and it works but I've this silly problem with alphabetical months.
I have the following code in a simple Bootstrap html file which displays a Chart.js chart.
this is chart.html
<head>
<meta charset="utf-8" />
<title>Chart.js </title>
<!-- import plugin script -->
<script src='app/static/js/Chart.min.js'></script>
</head>
<body>
<div class="chartjs">
<h1>Flask Chart.js</h1>
<!-- bar chart canvas element -->
<canvas id="chart" width="600" height="400"></canvas>
</div>
<script>
// bar chart data
var barData = {
labels : [{% for item in labels %}
"{{item}}",
{% endfor %}],
datasets : [
{
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
bezierCurve : false,
data : [{% for item in values %}
{{item}},
{% endfor %}]
}]
}
Chart.defaults.global.animationSteps = 50;
Chart.defaults.global.tooltipYPadding = 16;
Chart.defaults.global.tooltipCornerRadius = 0;
Chart.defaults.global.tooltipTitleFontStyle = "normal";
Chart.defaults.global.tooltipFillColor = "rgba(0,0,0,0.8)";
Chart.defaults.global.animationEasing = "easeOutBounce";
Chart.defaults.global.responsive = false;
Chart.defaults.global.scaleLineColor = "black";
Chart.defaults.global.scaleFontSize = 16;
// get bar chart canvas
var mychart = document.getElementById("chart").getContext("2d");
steps = 10
max = 10
// draw bar chart
var LineChartDemo = new Chart(mychart).Line(barData, {
scaleOverride: true,
scaleSteps: steps,
scaleStepWidth: Math.ceil(max / steps),
scaleStartValue: 0,
scaleShowVerticalLines: true,
scaleShowGridLines : true,
barShowStroke : true,
scaleShowLabels: true,
bezierCurve: false,
});
</script>
</body>
the direction of Chart.min.js
it turns out the chart.js doesn't work
this is part of views.py which is concern with chart.html
#main.route('/chart', methods=['GET', 'POST'])
def chart():
labels = ["January","February","March","April","May","June","July","August"]
values = [10,9,8,7,6,4,7,8]
return render_template('chart.html', values=values, labels=labels)
I doubt if the js was not referenced correctly and there was something wrong with the chart.html.
I had a similar problem. It was solved by replacing labels and data parts with
{{labels | tojson}}
{{values | tojson}}
if they are lists.
I found the answer here
I am getting dynamically generated data from my Raspberry PI in .csv format and I want to make a webpage for my institute to analyze the waveform of the output . The main feature of this graph is that the graph should auto-update according to the modified data. How should I go about making this?
I am assuming that the solution you are looking for must work in HTML 5 and JavaScript where there is NO server side processing. The raspberry pi posts a file to the server.
We are using morris charts which is JavaScript library
http://morrisjs.github.io/morris.js/
Morris uses a json format
1: read the csv file
2: convert the csv data to a json object
3: initialise the chart
try this example csv data
"elapsed","value",b
"Oct-12",24,2
"Oct-13",34,22
"Oct-14",33,7
"Oct-15",22,6
"Oct-16",28,17
"Oct-17",60,15
"Oct-18",60,17
"Oct-19",70,7
"Oct-20",67,18
"Oct-21",86,18
"Oct-22",86,18
$(document).ready(function() {
$.ajax({
url: "linechartdata.csv",
success: function(data) {
processData(data)
}
});
});
function processData(data) {
var record_num = 3; // or however many elements there are in each row
var dataLines = data.split(/\r\n|\n/);
var entries = dataLines[0].split(',');
var records = [];
var headers = entries.splice(0, record_num);
console.log(dataLines.length)
for (var i = 1; i < dataLines.length; i++) {
var obj = dataLines[i].split(',');
if (obj.length == headers.length) {
var tarr = [];
for (var j = 0; j < headers.length; j++) {
//doing it this way to get strings and numbers
var field01;
var field02;
var field03;
if (j == 0) {
field01 = obj[j]
}
if (j == 1) {
field02 = obj[j]
}
if (j == 2) {
field03 = obj[j]
}
var o = {
elapsed: field01,
value: field02,
b: field03
}
records.push(o);
}
}
}
initChart(records)
}
function initChart(records) {
var chart = Morris.Line({
element: 'morris-chart-network',
data: records,
axes: false,
xkey: 'elapsed',
ykeys: ['value', 'b'],
labels: ['Download Speed', 'Upload Speed'],
yLabelFormat: function(y) {
return y.toString() + ' Mb/s';
},
gridEnabled: false,
gridLineColor: 'transparent',
lineColors: ['#5b6b79', '#a5a5a5'],
lineWidth: [2, 1],
pointSize: [0, 2],
fillOpacity: .7,
gridTextColor: '#999',
parseTime: false,
resize: true,
behaveLikeLine: true,
hideHover: 'auto'
});
};
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Morris Chart</title>
</head>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<body>
<div>Morris Chart</div>
<div id="morris-chart-network" style="width:800px;height:600px">
</div>
<div>
example
</div>
I have a google map this is my current code
<div class="cont" id="cont">
<p><script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['geochart']});
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['State', 'Province', 'G-Form Outlets'],
['ZA-GT', 'Gauteng', 10],
['ZA-WC', 'Western Cape', 5],
['ZA-EC', 'Eastern Cape', 2],
['ZA-NL', 'KwaZulu-Natal', 1],
['ZA-FS', 'Free State', 1],
['ZA-LP', 'Limpopo', 0],
['ZA-NW', 'North-West', 0],
['ZA-MP', 'Mpumalanga', 0],
['ZA-NC', 'Northern Cape', 0],
]);
var view = new google.visualization.DataView(data);
view.setColumns([1, 2]);
var geochart = new google.visualization.GeoChart(
document.getElementById('visualization'));
var options = {};
options['region'] = 'ZA';
options['resolution'] = 'provinces';
options['width'] = 500;
options['height'] = 500;
options['colors'] = ['#cccccc', '#C01E24'];
options['legend'] = 'none';
google.visualization.events.addListener(geochart, 'select', function() {
var selectionIdx = geochart.getSelection()[0].row;
var stateName = data.getValue(selectionIdx, 0);
var value = data.getValue(selectionIdx, 2);
if (value >= '1') {
window.open('http://e-track.co.za');}
});
geochart.draw(data, options);
}
google.setOnLoadCallback(drawVisualization);
</script>
<div id="visualization"></div>
</p>
</div>
It is working great the problem is I am trying to place it in a DIV Tag but it keeps throwing it over to the left of the page where i want to place it in the middle of the box basically
<head>
<style type="text/css">
div
{
margin: 0 auto;
}
</style>
</head>
Add <Head> part in your code... Thatsall
I'm following the official Chrome Extension tutorial called Chritter where they fetch tweets from Twitter and place them into the extension. I'm trying to do similar except im trying to fetch items from an xml file.
My XML
<xml>
<item>
<title>Title 1</title>
<description>Description 1</description>
<duration>55:00</duration>
<published>28/01/2011</published>
</item>
<item>
<title>Title 2</title>
<description>Description 2</description>
<duration>55:00</duration>
<published>28/01/2011</published>
</item>
</xml>
background.html
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var fetchFreq = 30000; // how often we fetch new items (30s)
var req; // request object
var unreadCount = 0; // how many unread items we have
var items; // all currently fetched items
getItems();
//setInterval(getItems, fetchFreq);
function getItems(){
req = new XMLHttpRequest();
req.open("GET", "http://urltoxml.com/xmlfile.xml", false);
req.onload = processItems;
req.send();
}
function processItems(){
xmlDoc = req.responseXML;
items = xmlDoc.getElementsByTagName("item");
unreadCount += items.length;
if (unreadCount > 0) {
chrome.browserAction.setBadgeBackgroundColor({
color: [255, 0, 0, 255]
});
chrome.browserAction.setBadgeText({text: '' + unreadCount});
}
items = xmlDoc.concat(items);
}
</script>
</head>
</html>
I don't know how to get the fetched items from the background.html and displayed onto the popup.html ?
popup.html
<html>
<head>
<link rel="stylesheet" href="popup.css" />
<script src="util.js"></script>
<script>
var bg; // background page
// timeline attributes
var timeline;
var template;
var title;
var link;
var description;
onload = setTimeout(init, 0); // workaround for http://crbug.com/24467
// initialize timeline template
function init() {
chrome.browserAction.setBadgeText({text: ''});
bg = chrome.extension.getBackgroundPage();
bg.unreadCount = 0;
timeline = document.getElementById('timeline');
template = xpath('//ol[#id="template"]/li', document);
title = xpath('//div[#class="text"]/span', title);
content = xpath('//div[#class="text"]/span', template);
update();
}
function update(){
// how to do this ?
// See Chritter example below with JSON,
// except i want to it with xml ?
}
</script>
</head>
<body>
<div id="body">
<ol id="timeline" />
</div>
<ol id="template">
<li>
<div class="text">
<a></a>
<span></span>
</div>
<div class="clear"></div>
</li>
</ol>
</body>
</html>
The way the Chritter extension does it only seems to work with JSON. Here is how they do it:
// update display
function update() {
var user;
var url;
var item;
for (var i in bg.tweets) {
user = bg.tweets[i].user;
url = 'http://twitter.com/' + user.screen_name;
// thumbnail
link.title = user.name;
link.href = openInNewTab(url);
image.src = user.profile_image_url;
image.alt = user.name;
// text
author.href = openInNewTab(url);
author.innerHTML = user.name;
content.innerHTML = linkify(bg.tweets[i].text);
// copy node and update
item = template.cloneNode(true);
timeline.appendChild(item);
}
}
Chritter background.html
<html>
<head>
<script type="text/javascript">
var fetchFreq = 30000; // how often we fetch new tweets (30s)
var req; // request object
var unreadCount = 0; // how many unread tweets we have
var tweets; // all currently fetched tweets
getTweets();
setInterval(getTweets, fetchFreq);
// fetch timeline from server
function getTweets() {
req = new XMLHttpRequest();
req.open('GET', 'http://twitter.com/statuses/public_timeline.json');
req.onload = processTweets;
req.send();
}
// process new batch of tweets
function processTweets() {
var res = JSON.parse(req.responseText);
unreadCount += res.length;
if (unreadCount > 0) {
chrome.browserAction.setBadgeBackgroundColor({
color: [255, 0, 0, 255]
});
chrome.browserAction.setBadgeText({text: '' + unreadCount});
}
tweets = res.concat(tweets);
}
</script>
</head>
</html>
Any help much appreciated! Thanks!
If you want to access items var from a background page then:
var items = chrome.extension.getBackgroundPage().items;
I am not sure what the exact question is, but the general practice is to store the data from background page into localstorage and then access this data from the popup page.
http://www.rajdeepd.com/articles/chrome/localstrg/LocalStorageSample.htm