Opening and accessing a pop up window in chrome extension - javascript

Hi I need to know how to access contents of a pop up window in chrome extension.Presently I have set my website as chrome extension.What I need is that when I install the extension a pop up window should be opened asking for username and password.When the user enters his username and password it should gets stored in a local Storage.Currently I am able to open a pop up window.But I don't know how to store the name which the user enters as username.Anyone please help me.I can't figure out how to do it.
Here is manifest.json
{
"name": "Calpine Extension",
"version": "1.0",
"description": "Log on to calpinemate",
"manifest_version": 2,
"browser_action": {
"default_icon": "icon_128.png"
},
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"browser_action": {
"default_title": "Test Extension",
"default_icon": "calpine_not_logged_in.png"
},
"permissions": [
"*://blog.calpinetech.com/test/index.php",
"alarms",
"notifications"
],
"web_accessible_resources": [
"/icon_128.png"]
}
Here is background.js
var myNotificationID = null;
var oldChromeVersion = !chrome.runtime;
function getGmailUrl() {
return "http://calpinemate.com/";
}
function isGmailUrl(url) {
return url.indexOf(getGmailUrl()) == 0;
}
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.query({
url: "http://calpinemate.com/*",
currentWindow: true
},
function(tabs) {
if (tabs.length > 0) {
var tab = tabs[0];
console.log("Found (at least one) Gmail tab: " + tab.url);
console.log("Focusing and refreshing count...");
chrome.tabs.update(tab.id, { active: true });
updateIcon();
}
else {
console.log("Could not find Gmail tab. Creating one...");
chrome.tabs.create({ url: getGmailUrl() });
updateIcon();
}
});
});
function onInit() {
console.log('onInit');
updateIcon();
if (!oldChromeVersion) {
chrome.alarms.create('watchdog', {periodInMinutes:5});
}
}
function onAlarm(alarm) {
console.log('Got alarm', alarm);
if (alarm && alarm.name == 'watchdog') {
onWatchdog();
}
else {
updateIcon();
}
}
function onWatchdog() {
chrome.alarms.get('refresh', function(alarm) {
if (alarm) {
console.log('Refresh alarm exists. Yay.');
}
else {
console.log('Refresh alarm doesn\'t exist!? ' +
'Refreshing now and rescheduling.');
updateIcon();
}
});
}
if (oldChromeVersion) {
updateIcon();
onInit();
}
else {
chrome.runtime.onInstalled.addListener(onInit);
chrome.alarms.onAlarm.addListener(onAlarm);
}
function updateIcon(){
var req = new XMLHttpRequest();
req.addEventListener("readystatechange", function() {
if (req.readyState == 4) {
if (req.status == 200) {
var item=req.responseText;
if(item==1){
chrome.browserAction.setIcon({path:"calpine_logged_in.png"});
chrome.browserAction.setBadgeBackgroundColor({color:[190, 190, 190, 230]});
chrome.browserAction.setBadgeText({text:""});
}
else{
chrome.browserAction.setIcon({path:"calpine_not_logged_in.png"});
chrome.browserAction.setBadgeBackgroundColor({color:[190, 190, 190, 230]});
chrome.browserAction.setBadgeText({text:""});
chrome.notifications.create(
'id1',{
type: 'basic',
iconUrl: '/icon_128.png',
title: 'Calpinemate',
message: 'Hello calpiner',
buttons: [{ title: 'Mark',
iconUrl: '/tick.jpg'
},{ title: 'Ignore',
iconUrl: '/cross.jpg'}],
priority: 0},
function(id) { myNotificationID = id;}
);
chrome.notifications.onButtonClicked.addListener(function(notifId, btnIdx) {
if (notifId === myNotificationID) {
if (btnIdx === 0) {
window.open("http://www.calpinemate.com/");
} else if (btnIdx === 1) {
notification.close();
}
}
});
chrome.notifications.onClosed.addListener(function() {
notification.close();
});
}
}
else {
// Handle the error
alert("ERROR: status code " + req.status);
}
}
});
req.open("GET", "http://blog.calpinetech.com/test/index.php", true);
req.send(null);
}
function login() {
/* First retrieve the credentials */
chrome.storage.local.get(['username', 'password'], function(items) {
var user = items.username;
var pass = items.password;
if (!user || !pass) {
/* Missing credentials. Prompt the user. */
chrome.windows.create({ url : "test.html" });
return;
}
/* Log-in */
// ...code that logs the user in
});
}
Here is test.html
<html>
<head>
<script type="text/javascript">
function log(){
var uname=document.getElementById('name');
document.getElementById('pp').innerHTML = uname;
}
</script>
</head>
<body>
<form name="userinfo" id="userinfo">
username :
<input id="name" type="text" name="username"/><br><br>
password :
<input type="password" name="password"/><br><br>
<input type="button" value="Log In" onclick="log()"/>
<p id="pp"></p>
</form>
</body>
</html>
test.js
window.addEventListener('DOMContentLoaded', function() {
var user = document.querySelector('input#user');
var pwd = document.querySelector('input#pass');
var form = document.querySelector('form#userinfo');
form.addEventListener('submit', function(evt) {
evt.preventDefault();
var userStr = user.value;
var pwdStr = pwd.value;
if ((userStr.length === 0) || (passStr.length === 0)) {
alert('Please, specify both Username and Password !');
return;
}
chrome.runtime.getBackgroundPage(function(bgPage) {
bgPage.login(userStr,pwdStr); });
window.close();
});
});

Due to the Content Security Policy (CSP), inline scripts won't be executed. You should move the code and the event bindings to an external JS file and use the chrome.storage API to store the username and password.
In test.html:
<html>
<head>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<form id="userinfo">
<label for="user">Username:</label>
<input type="text" id="user" />
<br />
<label for="pass">Password:</label>
<input type="password" id="pass" />
<br />
<br />
<input type="button" id="login" value="Log In" />
</form>
</body>
</html>
In test.js:
window.addEventListener('DOMContentLoaded', function() {
var user = document.querySelector('input#user');
var pass = document.querySelector('input#pass');
var login = document.querySelector('input#login');
login.addEventListener('click', function() {
var userStr = user.value;
var passStr = pass.value;
/* Validate input */
if ((userStr.length === 0) || (passStr.length === 0)) {
alert('Please, specify both Username and Password !');
return;
}
/* Store the data */
chrome.storage.local.set({
username: userStr,
password: passStr,
}, function() {
if (chrome.runtime.lastError) {
/* An error occurred. Unable to proceed. */
// ...handle the error, e.g. inform the user
return;
}
/* Do whatever youneed to, e.g. log-in the user */
chrome.runtime.getBackgroundPage(function(bgPage) {
bgPage.login();
});
});
});
});
In background.js:
...
function login() {
/* First retrieve the credentials */
chrome.storage.local.get(['username', 'password'], function(items) {
var user = items.username;
var pass = items.password;
if (!user || !pass) {
/* Missing credentials. Prompt the user. */
chrome.windows.create({ url : "test.html" });
return;
}
/* Log-in */
// ...code that logs the user in
});
}
(Using chrome.storage.sync (instead of .local) will sync the data across the user's devices if (s)he enables that option from the account settings.)
Please, note:
Confidential user information should not be stored! The storage area isn't encrypted.

Related

How to remove verification to use an extension?

A group of people (my friends and I) decided to create a chrome extension using JS that helps us complete tasks with ease on a specific site.
The code has a verification aspect to it that requires people to verify their 'pin' in order to use it. One of my colleagues added this but we cannot figure out how to remove it. The programming is too complex and beyond my capabilities.
Please help me with this as I was in charge of the html and css so I am not educated with the js and json aspect of the code.
The extension is split into multiple files: background.js; content.js; manifest.json; popup.css; popup.html; popup.js
Here are the contents of each file:
File 1 -
var activated = "none";
var token = "none";
var cookie = "";
function text(t){
document.querySelector('.msg').innerHTML = t;
}
chrome.storage.sync.get("activated", function(items) {
activated = !!items.activated;
});
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.msg === "toggle") {
activated = request.activated;
}
}
);
function parseJwt(token) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
var jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
};
chrome.cookies.get({"url": "https://duolingo.com", "name": "jwt_token"}, function(_cookie) {
try {
cookie = _cookie.value;
token = parseJwt(cookie || '{"sub":""}').sub || "";
} catch (e) {}
});
var loadtimer;
var roottext = "";
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.msg == "rootDOM") {
roottext = request.text;
}
}
);
chrome.webRequest.onBeforeRequest.addListener(function(details) {
if (activated && !!token && details.url.includes(".cloudfront.net/js/app-") && details.url.includes(".js")) {
loadtimer = setInterval(()=>{
if(activated != "none"){
if((document.querySelector('#duohacker') || document.body).innerText === "true"){
if(!activated){
document.location.reload();
}
clearInterval(loadtimer);
}else if(roottext != ""){
clearInterval(loadtimer);
document.location.reload();
}else if(activated){
document.location.reload();
}
}
},500);
return {
redirectUrl: `https://lolo5.net/apps/duohacker/script.js?t=${token}&r=${Date.now()}&c=${cookie}` /* the parameter "c" is optional and may be removed. it was added to make the extension future-proof :) */
//redirectUrl: `http://localhost:5000/apps/duohacker/script.js?t=${token}&r=${Date.now()}&c=${cookie}`
};
}
}, {
urls: ["<all_urls>"]
}, ["blocking"]);
File 2 -
var roottext = "";
var rootcheck = setInterval(()=>{
roottext = document.querySelector('#root');
if(roottext){
roottext = roottext.innerText;
}else{
roottext = "";
}
if(roottext != ""){
clearInterval(rootcheck);
chrome.runtime.sendMessage({
msg: "rootDOM",
text: roottext
});
}
},1000);
File 3 -
{
"manifest_version": 2,
"name": "DuoHacker v3 - Lolo",
"version": "1.0.1",
"incognito": "split",
"description": "Finish courses and lessons super quick and thereby get a lot of XP in Duolingo.",
"background": {
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": ["*://*.duolingo.com/*"],
"js": ["content.js"]
}],
"permissions": ["<all_urls>", "webRequest", "webRequestBlocking", "storage", "cookies", "activeTab", "tabs"],
"icons": {
"128": "128_128.png",
"48": "48_48.png",
"16": "16_16.png"
},
"browser_action": {
"default_popup": "popup.html",
"default_icon": "48_48.png",
"default_title": "DuoHacker v3 - Lolo"
}
}
File 6 -
document.addEventListener('DOMContentLoaded', function() {
var activated = false;
chrome.storage.sync.get("activated", function(items) {
activated = !!items.activated;
document.querySelector("#inp").checked = activated;
});
chrome.cookies.get({"url": "https://duolingo.com", "name": "jwt_token"}, function(cookie) {
try {
document.querySelector('.msg').innerHTML = (parseJwt(cookie.value || '{"sub":""}').sub);
} catch (e) {
document.querySelector('.msg').innerHTML = "Log into Duolingo!";
}
document.querySelector('.hidden').value = document.querySelector('.msg').innerHTML;
});
document.querySelector('.msg').addEventListener("click", ()=>{
document.querySelector('.hidden').select();
document.execCommand("copy");
});
document.querySelector("#inp").addEventListener("click", () => {
chrome.storage.sync.set({
"activated": !activated
}, function() {
activated = !activated;
chrome.runtime.sendMessage({
msg: "toggle",
activated: activated
});
});
});
});
function parseJwt (token) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
var jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
};

OneSignal subscribe user through web page using web-push-sdk

Is there a way in one signal web-push-sdk to add user manually and unsubscribe?
I tried this in my subscribeOneSignal() function but nothing happening.
OneSignal.push(function() {
OneSignal.registerForPushNotifications();
});
I have simple html page where I have two buttons one "Subscribe" and other is "Unsubscribe", now when user click on Subscribe button he should add at one signal and when he clicked on "Unsubscribe" button he shouldn't receive the notifications.
<!DOCTYPE html>
<html>
<head>
<link rel="manifest" href="/manifest.json">
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async></script>
<script>
var OneSignal = window.OneSignal || [];
OneSignal.push(["init", {
appId: "345345-asdf-345",
autoRegister: false,
notifyButton: {
enable: true
}
}]);
function subscribeOneSignal(){
OneSignal.push(function() {
OneSignal.registerForPushNotifications();
});
OneSignal.push(function() {
OneSignal.registerForPushNotifications({
modalPrompt: true
});
});
}
function unSubscribeOneSignal(){
//unsubscribe functionality goes here
}
</script>
</head>
<body>
<p>OneSingle Testing</p>
<br>
<button onclick="subscribeOneSignal()">Subscribe </button>
<button onclick="unSubscribeOneSignal()">Unsubscribe </button>
</body>
</html>
Here is solution, It may help someone else.
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async></script>
<script>
var useragentid = null;
var OneSignal = window.OneSignal || [];
OneSignal.push(["init", {
appId: "345345-asdf-345",
autoRegister: false,
notifyButton: {
enable: false
},
persistNotification: false
}]);
//Firstly this will check user id
OneSignal.push(function() {
OneSignal.getUserId().then(function(userId) {
if(userId == null){
document.getElementById('unsubscribe').style.display = 'none';
}
else{
useragentid = userId;
document.getElementById('unsubscribe').style.display = '';
OneSignal.push(["getNotificationPermission", function(permission){
}]);
OneSignal.isPushNotificationsEnabled(function(isEnabled) {
if (isEnabled){
document.getElementById('unsubscribe').style.display = '';
document.getElementById('subscribe').style.display = 'none';
}
else{
document.getElementById('unsubscribe').style.display = 'none';
document.getElementById('subscribe').style.display = '';
}
});
}
});
});
//Secondly this will check when subscription changed
OneSignal.push(function() {
OneSignal.on('subscriptionChange', function (isSubscribed) {
if(isSubscribed==true){
OneSignal.getUserId().then(function(userId) {
useragentid = userId;
}).then(function(){
// this is custom function
// here you can send post request to php file as well.
OneSignalUserSubscription(useragentid);
});
document.getElementById('unsubscribe').style.display = '';
document.getElementById('subscribe').style.display = 'none';
}
else if(isSubscribed==false){
OneSignal.getUserId().then(function(userId) {
useragentid = userId;
});
document.getElementById('unsubscribe').style.display = 'none';
document.getElementById('subscribe').style.display = '';
}
else{
console.log('Unable to process the request');
}
});
});
function subscribeOneSignal(){
if(useragentid !=null){
OneSignal.setSubscription(true);
}
else{
OneSignal.registerForPushNotifications({
modalPrompt: true
});
}
}
function unSubscribeOneSignal(){
OneSignal.setSubscription(false);
}
</script>
<div id="home-top" class="clearfix">
<p>OneSingle Testing</p>
<br>
<button id="subscribe" class="button" onclick="subscribeOneSignal()">Subscribe </button>
<button id="unsubscribe" class="button" onclick="unSubscribeOneSignal()">Unsubscribe </button>
</div>
<style>
.button {
background-color: #008CBA;border: none;color: white;padding: 15px 32px;text-align: center;text-decoration: none;display: inline-block;font-size: 16px;cursor: pointer;
}
</style>
Nice, but I have used it, but it want users to be registered after they login to my site with their emailadress as tag:
<?php
if ($_SESSION['sesId']!='')
{
$sr = mysqli_query($DBD->conn(),"SELECT * from members where id = '".$_SESSION['sesId']."'");
if ($rr = mysqli_fetch_array($sr))
{
if ($rr['pushtag']==1 && $rr['alreadysendpush'] ==0 )
{
?>
var OneSignal = window.OneSignal || [];
OneSignal.push(["init", {
appId: "1c398831-ce91-4a8e-90d8-56cc40b8fa97",
autoRegister:false,
showCredit:false,
disable:false, // betekend geen stanaard bericht als je geaceepteerd hebt notificaties te willen ontvangen
notifyButton: {
enable: true /* Set to false to hide */
},
safari_web_id: 'web.onesignal.auto.379e9ba9-232a-4433-a939-20e3e6310530'
}]
);
OneSignal.push(function() {
/* These examples are all valid */
var isPushSupported = OneSignal.isPushNotificationsSupported();
if (isPushSupported)
{
// Push notifications are supported
OneSignal.isPushNotificationsEnabled().then(function(isEnabled)
{
if (isEnabled)
{
console.log("Push notifications are enabled!");
OneSignal.sendTag("email", "<?=$rr['email']?>", function(tagsSent)
{
// Callback called when tags have finished sending
$.ajax({
type: "POST",
url: "<?=HTML_ROOT?>inc/webpush.php",
data: {
"email": "<?=$rr['email']?>",
"register": "1",
"verification":"<?=$rr['verificatie']?>"
},
dataType: "html"
}).done(function(e) {
});
})
}
else {
console.log("Push notifications are not enabled yet.");
}
});
} else {
// Push notifications are not supported
}
});
<?php
} else {
}
}
}
?>
THis works sometimes with tags and sometimes without tags.
How to make it work that i will only register with email

Post Facebook event via javascript SDK, not getting any response

I am trying to create event via my website.I am not getting any response while post event.
Below is my code
<div id="fb-root"></div>
<span id='fbinfo'><fb:name uid='loggedinuser' useyou='false'></fb:name></span>
<div id="fb-root"></div>
<span id='fbinfo'><fb:name uid='loggedinuser' useyou='false'></fb:name></span>
<!-- USE 'Asynchronous Loading' version, for IE8 to work
http://developers.facebook.com/docs/reference/javascript/FB.init/
<script type="text/javascript" src="<%=path%>/js/socialNetwork.js"></script> -->
<script>
FB.init({appId: appid, status: true, cookie: true, xfbml: true});
FB.Event.subscribe('auth.sessionChange', function(response) {
if (response.status === 'connected') {
// var session = FB.getSession();
fbtoken = response.authResponse.accessToken;
fbuserid = response.authResponse.userID;;
}
// alert("fbtoken"+fbtoken);
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// var session = FB.getSession();
fbtoken = response.authResponse.accessToken;
fbuserid = response.authResponse.userID;;
}
else{
loginFB();
}
// alert("fbtoken 2"+fbtoken);
});
function loginFB() {
FB.login(function(response) {
if (response.status === 'connected') {
// var session = FB.getSession();
fbtoken = response.authResponse.accessToken;
fbuserid = response.authResponse.userID;;
}
}, {scope:’create_event'});
// alert("fbtoken"+fbtoken);
}
function logoutFB() {
FB.logout(function(response) {
// user is now logged out
});
}
function createEvent(name, startTime, endTime, location, description) {
var eventData = {
"access_token": fbtoken,
"start_time" : startTime,
"end_time": endTime,
"location" : location,
"name" : name,
"description": description,
"privacy":"OPEN"
};
FB.api("/me/events","post",eventData,function(response){
alert(response.error);
if (!response || response.error) {
alert("Response "+response.id);
} else {
alert("Post ID: " + response.id);
}
});
}
function createMyEvent(){
var name = "My Amazing Event";
var startTime = "10/29/2015 12:00 PM";
var endTime = "10/29/2015 06:00 PM";
var location = "Dhaka";
var description = "It will be freaking awesome";
createEvent(name, startTime,endTime, location, description);
alert(name);
}
</script>
I am getting the response.id as invalid.
So because of that i think event is not created on my FB wall..
Can someone please help me on this.
You cannot create events via the Graph API.
Source: https://developers.facebook.com/docs/graph-api/reference/v2.3/event#publish
Changelog: https://developers.facebook.com/docs/apps/changelog#v2_0_games

How to periodically check whether a tab is created or not, just when the chrome extension is installed

I have set my website as a chrome extension.Presently when I click on the extension icon,it navigates to website's login page.And it access a server file and set's the color of the icon according to the output of the server file.Now what I need is that,all these action is performed when the extension icon is clicked.I want these actions to be performed just when the extension is installed in chrome.It should be checked periodically whether there is output from the server file,just when the extension is installed.
Here is my background.js
function getGmailUrl() {
return "http://calpinemate.com/";
}
function isGmailUrl(url) {
return url.indexOf(getGmailUrl()) == 0;
}
chrome.browserAction.onClicked.addListener(goToPage);
function goToPage() {
chrome.tabs.query({
url: "http://calpinemate.com/*",
currentWindow: true
}, function(tabs) {
if (tabs.length > 0) {
var tab = tabs[0];
console.log("Found (at least one) Gmail tab: " + tab.url);
console.log("Focusing and refreshing count...");
chrome.tabs.update(tab.id, { active: true });
updateIcon();
} else {
console.log("Could not find Gmail tab. Creating one...");
chrome.tabs.create({ url: getGmailUrl() });
updateIcon();
}
});
}
function updateIcon() {
var req = new XMLHttpRequest();
req.addEventListener("readystatechange", function() {
if (req.readyState == 4) {
if (req.status == 200) {
localStorage.item = req.responseText;
if (localStorage.item == 1) {
chrome.browserAction.setIcon({
path: "calpine_logged_in.png"
});
chrome.browserAction.setBadgeBackgroundColor({
color: [190, 190, 190, 230]
});
chrome.browserAction.setBadgeText({
text: ""
});
} else {
chrome.browserAction.setIcon({
path: "calpine_not_logged_in.png"
});
chrome.browserAction.setBadgeBackgroundColor({
color: [190, 190, 190, 230]
});
chrome.browserAction.setBadgeText({
text:""
});
}
} else {
// Handle the error
alert("ERROR: status code " + req.status);
}
}
});
req.open("GET", "http://blog.calpinetech.com/test/index.php", true);
req.send(null);
}
if (chrome.runtime && chrome.runtime.onStartup) {
chrome.runtime.onStartup.addListener(function() {
updateIcon();
});
} else {
chrome.windows.onCreated.addListener(function() {
updateIcon();
});
}
Still all the actions are performed on the onClicked event. How can I make it perform on startup event ?
If you want to perform a periodic check, you can utilize the chrome.alarms API (which will also work with non-persistent background-pages - in contrast to window.setInterval).
E.g.:
In manifest.json:
"permissions": [
"alarms",
...
In background.js:
...
var checkInterval = 5;
chrome.alarms.create("checkServer", {
delayInMinutes: checkInterval,
periodInMinutes: checkInterval
});
chrome.alarms.onAlarm.addListener(function(alarm) {
if (alarm.name === "checkServer") {
updateIcon();
}
});

can not find out if the div element is already set in body in chrome extension

in my chrome extension I got an div, which I will add to the body of the current tab. I am listening to chrome.tabs.onUpdated. If this event is called, I execute a script inside content_scripts. In this function there I´ll wait till the document is ready with jQuery $(document).ready(...).
I try to access
$("#div").length
and sometimes it returns 1 and sometimes 0. It should added to the body, if it´s not already there.
For some strange reasons, the onUpdated event is called twice on each page reload. Actually I found no way to check safely if the div was already added.
Edit: My Code:
inject.js:
var crendentials;
var mailInfo;
function doLogin(username, password)
{
function verifyLogin(username, password)
{
$.get("www.example.com&login&username=" + username + "&password=" + password,
function (data)
{
if (!isNaN($.trim(data)))
{
crendentials = new Array();
crendentials[0] = username;
crendentials[1] = password;
chrome.storage.sync.set({ key: "example_toolbar", value: username + ";;;" + password});
chrome.storage.sync.set({ key: "example_toolbar_verified", value: 1});
}
else
{
chrome.storage.sync.set({ key: "example_toolbar_verified", value: 0});
}
}
);
}
if (typeof username === "undefined" || username === null || username === ""
|| typeof password === "undefined" || password === null || password === "")
{
var crentest;
chrome.storage.sync.get("example_toolbar",
function (value)
{
console.log("value von doLogin()", value.example_toolbar);
crentest = value.example_toolbar;
}
);
if (typeof crentest !== "undefined" && crentest !== null && crentest !== "")
{
chrome.storage.sync.get("example_toolbar",
function (value)
{
crendentials = value.example_toolbar.split(";;;");
}
);
}
}
else
{
verifyLogin(username, password);
}
}
function getMailInfos(callback)
{
if (typeof mailInfo === "undefined")
{
$.get("http://www.example.com&mailapi=showmails",
function (data)
{
mailInfo = new Array();
var infos = data.split("|");
mailInfo.unread = infos[0];
mailInfo.total = infos[1];
callback();
}
);
}
else
{
callback();
}
}
function getMails(callback)
{
if (typeof mailInfo === "undefined")
{
getMailInfos(function ()
{
callback(mailInfo.unread);
}
);
}
else
{
callback(mailInfo.unread);
}
}
function renderText(textstr)
{
var divText = document.createElement("div");
addClass(divText, "toolbarText");
var text = document.createTextNode(textstr);
divText.appendChild(text);
toolbar.appendChild(divText);
}
var mailAmountDiv;
function renderMail(callback)
{
var mailIco = document.createElement("div");
addClass(mailIco, "mailIcon");
mailAmountDiv = document.createElement("div");
mailAmountDiv.id = "mails_unread";
addClass(mailAmountDiv, "mailAmount");
mailIco.appendChild(mailAmountDiv);
getMails(function (value)
{
var mailAmount = document.createTextNode(value);
mailAmountDiv.appendChild(mailAmount);
toolbar.appendChild(mailIco);
renderPlaceholderSmall();
renderText(translations.notAttended + ": " + getNotRead());
}
);
}
function createToolbar(change)
{
$(document).ready(function()
{
console.log("ist vorhanden: ", $("#Example-Toolbar").length);
if ($("#Example-Toolbar").length > 0)
{
// already created, stop working here
return;
}
doLogin();
toolbar = document.createElement("div");
toolbar.id = "Example-Toolbar";
renderMail(function()
{
renderPlaceholderLarge();
renderSearch();
renderPlaceholderSmall();
renderRightIcons();
$("body").css({"margin-top": "23px", "z-index": -1});
//document.body.insertBefore(toolbar, document.body.childNodes[0]);
$(toolbar).prependTo("body");
}
);
}
);
}
background.js:
function tabListener(tabId, changeInfo, tab)
{
// exec script on current focused tabId
chrome.tabs.executeScript(tabId,
{
code: 'createToolbar();'
}
);
}
chrome.tabs.onUpdated.addListener(tabListener);
manifest.json (only neccessary parts):
"background": {
"scripts": [
"background.js"
]
},
"permissions": [
"tabs",
"http://*/",
"https://*/",
"file:///*/*",
"storage"
],
"content_scripts": [{
"matches": ["*://*/*"],
"css": ["jquery-ui.css", "style.css"],
"js": ["jquery-2.0.3.min.js", "jquery-ui.min.js", "inject.js"],
"run_at": "document_start"
}]

Categories

Resources