Chrome, recognize open tab - notifications

I'm creating an extenstion for google chrome that will perform checking if a stream on twitch.tv is online and will notify the user evey X minutes, I got that covered. What I'm looking for is a JScirpt code that will recognize if user is already on the streamers channel and will stop notifying him.
var username="$user";
setInterval(check,300000);
function check()
{
request("https://api.twitch.tv/kraken/streams/" + username, function() {
var json = JSON.parse(this.response);
if (json.stream == null)
{
chrome.browserAction.setIcon({ path: "offline.png" });
}
else
{
notify();
}
});
return 1;
}
function notify(){
var opt = {type: "basic",title: username + " is streaming!",message: "Click to join!",iconUrl: "start.png"};
chrome.notifications.create("", opt, function(notificationId)
{
setTimeout(function()
{
chrome.notifications.clear(notificationId, function(wasCleared) { console.log(wasCleared); });
}, 3000);
});
chrome.browserAction.setIcon({path:"online.png" });
}
chrome.browserAction.onClicked.addListener(function () {
chrome.tabs.create({ url: "http://www.twitch.tv/"+username });
});
function request(url, func, post)
{
var xhr = new XMLHttpRequest();
xhr.onload = func;
xhr.open(post == undefined ? 'GET' : 'POST', url, true);
xhr.send(post || '');
return 1;
}
check();

Use window.location.href to get the complete URL.
Use window.location.pathname to get URL leaving the host.
You can read more here.

Related

Is there a way to fix Cannot read property 'post' of undefined?

I'm running a page in vue with a form, it submits and returns data to and from an API, I'm getting a 'post' of undefined error in the console and I can't seem to figure out what's going on.
<script>
methods: {
StartClient: function () { // Initiate XMLHttpRequest as aHttpRequest for GET
this.get = function(Url, Callback){
var aHttpRequest = new XMLHttpRequest();
aHttpRequest.onreadystatechange = function() {
if (aHttpRequest.readyState == 4 && aHttpRequest.status == 200)
Callback(aHttpRequest.responseText);
}
// use aHttpRequest with response headers, to allow GET
aHttpRequest.open("GET", Url, true);
aHttpRequest.setRequestHeader("X-Api-Key", "eVnbxBPfn01kuoJIdfgi46TiYNv8AIip1r3WbjsX");
aHttpRequest.send(null);
}
this.post = function(Url, message, Callback) { // initiate XMLHttpRequest as aHttpRequest for POST
var aHttpRequest = new XMLHttpRequest();
aHttpRequest.onreadystatechange = function() {
if (aHttpRequest.readyState == 4 && aHttpRequest.status == 200)
Callback(aHttpRequest.responseText);
}
// use aHttpRequest with response headers, to allow POST
aHttpRequest.open("POST", Url, true);
aHttpRequest.setRequestHeader("X-Api-Key", "eVnbxBPfn01kuoJIdfgi46TiYNv8AIip1r3WbjsX");
aHttpRequest.send(message);
}
},
submitData: function () { // Start a traceroute, followed by the 'Begin' button
document.getElementById('inputBox').disabled = true;
var targetInputButton = document.getElementById("inputBox").value;
var message = '{"targetInputButton":"' + targetInputButton + '"}';
this.StartClient().post('https://le75bkfcmg.execute-api.eu-west-2.amazonaws.com/dev/start-trace', message, function(response) {
document.getElementById('jobId').innerHTML = response;
});
},
sendBackData: function () { // Receive traceroute data, followed by the 'Generate data' button
var jobId = document.getElementById("jobId").innerHTML;
var message = '{"jobId":"' + jobId + '"}';
this.StartClient().post('https://le75bkfcmg.execute-api.eu-west-2.amazonaws.com/dev/check-trace', message, function(response) {
document.getElementById('report').innerHTML = response;
});
}
}
}
</script>

Twitter OAuth Ionic 2

Its possible generate a Twitter token and secret token in Nodejs and after use it to open the browser for authenticate with "https://api.twitter.com/oauth/authenticate"?
I use this way to get the token:
app.get('/auth/twitter/token', function (req, res) {
var requestTokenUrl = 'https://api.twitter.com/oauth/request_token';
var requestTokenOauth = {
consumer_key: "2z8MTR8KAZuFafPHsEQ0ZBgo1",
consumer_secret: "ksPiaQz7ihCrOh3m4iRCsXZzQuSkkmcv4CLGiJQwREWeaQl7St"
};
request.post({
url: requestTokenUrl,
oauth: requestTokenOauth
}, function (err, response, body) {
var oauthToken = qs.parse(body);
res.send(oauthToken);
});
});
When I get this token in the client "https://api.twitter.com/oauth/authenticate?oauth_token=TOKEN" I got this problem: "This page is no longer valid. It's looks like someone already used the token information your provider, blabla.."
The problem is due to the way that I get the Token?
I'm using ng2-cordova-auth but this lib dont have twitter auth, I'm just trying to implement
This is my implementation:
"use strict";
var utility_1 = require("../utility");
var PROVIDER_NAME = "Twitter";
var Twitter = (function () {
function Twitter(options) {
this.twitterOptions = options;
this.flowUrl = ""
}
Twitter.prototype.login = function (token, tokenSecret) {
var _this = this;
return new Promise(function (resolve, reject) {
_ this.flowUrl = "https://api.twitter.com/oauth/authenticate?oauth_token="+token;
var browserRef = window.cordova.InAppBrowser.open(_this.flowUrl);
browserRef.addEventListener("loadstart", function (event) {
if ((event.url).indexOf(_this.twitterOptions.redirectUri) === 0) {
browserRef.removeEventListener("exit", function (event) { });
browserRef.close();
var parsedResponse = event.url.split("?")[1].split("&");
if (parsedResponse) {
resolve(parsedResponse);
}
else {
reject("Problem authenticating with " + PROVIDER_NAME);
}
}
});
browserRef.addEventListener("exit", function (event) {
reject("The " + PROVIDER_NAME + " sign in flow was canceled");
});
});
};
return Twitter;
}());
exports.Twitter = Twitter;
In my component/controller I make this:
//With twitterToken I get the token from NodeJs
this.API.twitterToken().subscribe(
data => {
this.twitterOAuth.login(data.oauth_token, data.oauth_token_secret).then((success) => {
alert(JSON.stringify(success))
}, (error) => {
alert(JSON.stringify(error));
});
},
err => alert(JSON.stringify(err))
);
Have you tried the Twitter Connect plugin? Does this help?
Plugin to use Twitter Single Sign On Uses Twitter's Fabric SDK
An example of use is
import {TwitterConnect} from 'ionic-native';
function onSuccess(response) {
console.log(response);
// Will console log something like:
// {
// userName: 'myuser',
// userId: '12358102',
// secret: 'tokenSecret'
// token: 'accessTokenHere'
// }
}
TwitterConnect.login().then(onSuccess, onError);

PhantomJs Injecting jQuery in different pages

I have a PhantomJs script in which I create a new wepage, inject jQuery into it and scrape a list of URL from it. After that I call a function passing the list of URL and create a new webpage for each one and try to recover certain information from it
var pageGlobal = require('webpage');
function createPage(){
var page = pageGlobal.create();
page.onAlert = function(msg) {
console.log(msg);
};
return page;
}
var page=createPage();
page.open('http://www.example.com/', function(status){
if ( status === "success" ) {
page.injectJs('jquery-1.6.1.min.js');
var urlList=page.evaluate(
function(){
var urlList=[];
window.console.log = function(msg) { alert(msg) };
$("td.row1>a").each(function(index, link) {
var link=$(link).attr('href');
urlList.push(link);
});
return urlList;
});
processUrlList(urlList);
}
});
function processUrlList(urlList){
for(i=0;i<urlList.length;i++){
var currentPage=createPage();
currentPage.open("http://www.example.com"+urlList[i], function(status){
if ( status === "success" ) {
if(currentPage.injectJs('jquery-1.6.1.min.js')===false){
console.log("Error en la inyeccion");
}
currentPage.evaluate(function() {
window.console.log = function(msg) { alert(msg) };
console.log("Evaluating");
$("showAdText").each(function(index, link) {
//Capture information about the entity in this URL
})
});
}
});
}
}
The problem is in the processUrlList function the injection of jQuery always fail returning false. Would it be a problem to create two or more page objects instead of reusing only one? What could be happening here?

JS and CSS file fails to load when the page is refreshed in grails application which uses Atmosphere Meteor plugin

In my grails 2.3.7 application,
I am using atmosphere-meteor 0.8.3.
On my home page load, I subscribe the client. And by default I run long-polling; and it works fine.
On page refresh, I unsubscribe the client.
However, if I refresh the page; then some of the JS and CSS fails to load. It happens 5 out of 10 times of refresh.
Am I doing anything wrong? (As I subscribe on document.ready()).
Or do I need to do anything else?
Any help is appreciated.
Update:
Code inside gsp for subscription:
$('body').bind('beforeunload',function(){
Jabber.unsubscribe();
});
$(document).ready(function () {
if (typeof atmosphere == 'undefined') {
Jabber.socket = $.atmosphere;
} else {
Jabber.socket = atmosphere;
}
var atmosphereRequest = {
type: 'public',
url: 'atmosphere/public',
trackMessageLength: false
};
//setTimeout(function(){
Jabber.subscribe(atmosphereRequest);
//}, 10000);
});
And the Jabber variable
var Jabber = {
socket: null,
publicSubscription: null,
transport: null,
subscribe: function (options) {
var defaults = {
type: '',
contentType: "application/json",
shared: false,
//transport: 'websocket',
transport: 'long-polling',
fallbackTransport: 'long-polling',
trackMessageLength: true
},
atmosphereRequest = $.extend({}, defaults, options);
console.log(atmosphereRequest);
atmosphereRequest.onOpen = function (response) {
console.log('atmosphereOpen transport: ' + response.transport);
};
atmosphereRequest.onReconnect = function (request, response) {
console.log("atmosphereReconnect");
};
atmosphereRequest.onMessage = function (response) {
console.log("on message");
Jabber.onMessage(response);
};
atmosphereRequest.onError = function (response) {
console.log('atmosphereError: ' + response);
};
atmosphereRequest.onTransportFailure = function (errorMsg, request) {
console.log('atmosphereTransportFailure: ' + errorMsg);
};
atmosphereRequest.onClose = function (response) {
console.log('atmosphereClose: ' + response);
};
switch (options.type) {
case 'public':
Jabber.publicSubscription = Jabber.socket.subscribe(atmosphereRequest);
break;
default:
return false;
}
//Jabber.publicSubscription = Jabber.socket.subscribe(atmosphereRequest);
},
unsubscribe: function () {
if (Jabber.socket)
Jabber.socket.unsubscribe();
},
onMessage:function(response){....}
}
I'm the plugin author. Please update to version 1.0.1. If you still have trouble after updating the plugin, create a new issue. We can work through the problem then. However, I do have a question. When you say the JS fails to load, do you mean the atmosphere JavaScript or your own? There is no plugin related CSS.

How to pass Client Side data to Server Side using Ember.js

I'm studying Ember.js myself and I'm stuck with a problem I'm creating a sample app and I need to send the client side values to Server Side but I dont know how to do that I know the traditional way like the below code
function create() {
var data = {
'EmailID': $('#emailid').val(),
'password': $('#password').val()
}
$.ajax({
url: '/EmberNew/Home/Create',
type: 'POST',
data:data,
success: function (response) {
alert("hi");
}
});
return false;
}
but In Ember i dont Know How to do that my current code is given below
//Application
App = Em.Application.create();
//Model
App.Users = Em.Object.extend({
name: null,
password:null
});
//View
App.UserTextField = Em.TextField.extend({
insertNew: function () {
App.alertController.alertDetails();
}
});
App.PassTextField = Em.TextField.extend({
insertNew: function () {
App.alertController.alertDetails();
}
});
//controller
App.AlertController = Em.ObjectController.extend({
content: [],
username: '',
password: '',
alertDetails: function () {
var me = this;
var username = me.get("username");
var password = me.get("password");
alert('The User Name Is' + 'username' + 'And Password Is' + 'password');
}
});
App.alertController = App.AlertController.create();
I got the textbox values from alertDetails function and how can I pass them to server side
App.Record = Ember.Object.extend({
name: '',
other: ''
}).reopenClass({
records: [],
find: function() {
var self = this;
$.ajax({
url: "/api/records/",
type: "GET",
cache: false,
dataType: "json",
beforeSend: function() {
//if you want to call this often and need to clear + reload it
return self.records.clear();
},
success: function(results) {
var result;
for (_i = 0, _len = results.length; _i < _len; _i++) {
result = results[_i];
self.records.push(self.records.addObject(App.Record.create(result)));
}
},
error: function() {
return alert("error: failed to load the records");
}
});
return this.records;
}
});
Now that you have your model setup, you can call it from your route model hook
App.RecordsRoute = Ember.Route.extend({
model: function() {
return App.Record.find();
}
});
The find method returns an empty array right away, your template is then bound to it. When the ajax call returns w/ success and you update that array the handlebars template will update it for you w/out any DOM or jQuery glue code