I'm trying to check cookie with chrome extension with following code
content.js
if (hostName == "google.com") {
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
if (response.farewell == null) {console.log("cookie is null");}
});
}
background.js
function getCookies(domain, name, callback) {
chrome.cookies.get({"url": domain, "name": name}, function(cookie) {
if(callback) {
callback(cookie.value);
}
});
}
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message.greeting == "hello") {
getCookies("http://www.google.com", "cookie_name", function(id) {
if (id) {
alert("cookie "+id);
sendResponse({farewell: id});
} else {
alert("cookie "+id);
sendResponse({farewell: id});
}
});
return true;
}
});
This code works if cookie is set. But there is no alert and response if there is no cookie.
How do I check if there is no cookie? What am I doing wrong?
Looking at the docs (here) cookie is null if there isn't a cookie, so cookie.value should be throwing an error in your background page like this: Cannot read property 'value' of null. Perhaps try testing for the null result in your getCookies function rather than in your message response.
Related
I read some of the chrome docs and got this basic example working.
Now I want to make the request based on an event happening. The event is triggered and contentUpdateData() runs, but the chrome.runtime.sendMessage within the function doesn't seem to work. Any ideas why?
/* content.js */
var data = []
chrome.runtime.onMessage.addListener(
function(request, sesnder, sendResponse) {
if (request.message === 'popupClicked') {
contentUpdateData();
}
}
)
function contentUpdateData() {
console.log('Code works up to here. Button clicked in popup.html, recieved in content.js. Need to get info from background.js')
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
data = response.data
});
}
/* background.js basic example from chrome */
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting === "hello")
sendResponse({farewell: "goodbye", data: null});
}
);
You need to return true from the event listener in backgroundjs. This saves sendResponse() from garbage collection.
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.greeting === "hello") sendResponse({ farewell: "goodbye", data: null });
// VERY IMPORTANT
return true;
});
Somehow the background.js did not sync properly after updating the extension. This was the cause for the error.
Background script
browser.runtime.onMessage.addListener(function (event) {
if( event.type === 'authenticate' ) {
browser.tabs.query({active: true}, function(tab) {
browser.tabs.sendMessage(tab[0].id, {
method: 'main',
auth0: "test"
}, function() {});
});
}
});
Content script
browser.runtime.sendMessage({
type: "authenticate"
});
browser.extension.onMessage.addListener(function(request, sender, sendResponse) {
if( request.method == 'main' ) {
login();
} else if( request.method == 'logout' ) {
logout();
}
sendResponse({});
});
The event goes through and the tab id is correct, but the debug info from firefox shows "Error: Could not establish connection. Receiving end does not exist."
On chrome the event callback goes through. Anyone know what the issue is? Looking through google I found something about the id not being correct but I'm not sure what the issue is here.
Using browser.runtime.onMessage and changing
browser.tabs.query({active: true}, function(tab) {
browser.tabs.sendMessage(tab[0].id, {
method: 'main',
auth0: "test"
}, function() {});
});
to
browser.tabs.query({active: true, currentWindow: true}, function(tab) {
chrome.tabs.sendMessage(tab[0].id, {
method: 'main',
auth0: "test"
});
});
fixed it for me.
I want to check if json data is empty or not.
if json its empty, i want to alert orders Not Found.
If its not empty, i want to alert orders found.
if user not logged in, there won't be any token in his localstorage. so he will get a 500 error when browser requests the API URL. then I want to alert failed along with the failed status reason
my dev is sick, so tried my self. its not going too well.
Tried the below code, not at all working.
<script>
$http.get("http://localhost.com/activeorders/?format=json",{
headers: {'Authorization': 'Token '+ localStorage.getItem("token")}})
.success(function(response) {
if(response=="[]")
{
alert(" orders NOT found");
}
else
{
alert("orders found");
}
.error(function(response,status) {
alert("failed");
alert(status);
}
return ;
});
</script>
Any help will be thankfull.
if you are trying to do in Angular js, then you can try the code below using callbacks:
$http({
method: 'GET',
url: 'http://localhost.com/activeorders/?format=json',
headers: {
'Authorization': 'Token '+ localStorage.getItem('token')
}
}).then(function successCallback(response){ // this callback will be called asynchronously when the response is available
if (response.data.length == 0){
console.log("orders NOT found")
}
// or if you just return an array json by php for example
//if (response.length == 0) {
//console.log("orders NOT found")
//}
}, function errorCallback(response){ // called asynchronously if an error occurs or server returns response with an error status.
if (response){
alert("failed");
}
});
If you are using an external file .json type, you can try :
menuApp.controller("dynamicMenuController", function($scope, $http) {
$http.get('config/menu.json').success(function(data) {
console.log("success!");
if(data.length == 0){
alert('empty');
}
else {alert('some here!')}
});
If your json is in another domain, an external domain . In this case , I suggest you look at JSONP instead, here's an example http://fdietz.github.io/recipes-with-angular-js//consuming-external-services/consuming-jsonp-apis.html:
$http.jsonp('http://teckstack.com/api/get_recent_posts/?callback=JSON_CALLBACK').success(function (data) {
console.log("success callback");
if(data.length == 0){
alert('empty');
} // response data
}).error(function (data) {
console.log("failed callback");
});
If you want to check if a JS object or JSON is empty ({}), for example, your object is response:
Object.keys(response).length === 0 && response.constructor === Object
Try
if( Object.keys(JSON.parse(response)).length == 0 ){
alert("err")
}
I'm having an issue with a facebook app on Android 4.3 (and maybe other versions but 5 & 6 seem okay).
It's a web app, users can share pictures and their friends can go and vote for it, but they have to be logged in to the app. I'm using the JS SDK.
Facebook opens the link in it's own browser and the FB.login seem to fail. I have an "unknown" status so I try a FB.login and nothing seems to happen...
If I open the same link in chrome, everything works fine, Facebook asks for the permissions (after i got a "not_authorized" status) and I can vote.
Is there a way to make it work with the old versions of the facebook browser ? Or maybe a way to know the user is using this old browser so I can put an error message?
See comments for the fiddle
// Rate a picture
function rateApic(domLink) {
var $link = $(domLink);
$.ajax({
url: '/rateAPicture',
type: 'POST',
dataType: 'json',
data: {
id: $link.attr('data-entry')
},
success: function(result, status) {
var content = result.message;
switch (result.returnCode) {
case 0: // OK
$link.parent().find('.nbRatings').html(result.nbRatings); // rate number +1
popupManager(content); // display success message
break;
case 1: // Not logged in
loginFb('rateAphoto', $link);
break;
default:
popupManager(content); // display error message
}
},
error: function(result, status, error) {},
complete: function(result, status) {}
});
};
// Check user login state
function checkLoginState() {
var status = "";
FB.getLoginStatus(function(response) {
status = response.status;
});
return status;
}
// Connect to facebook app
function loginFb(redirectUrl, object) {
var loginState = checkLoginState();
if (loginState === 'unknown' || loginState === "not_authorized" || loginState == undefined) {
// within Facebook's app built-in browser on Adroid (4.3 & 5.1.1 and other versions but 6.0.1 is okay)
// loginState is always unknown
FB.login(function(response) {
if (response.status === 'connected') {
loginToApp(redirectUrl, object);
};
}, {
scope: 'public_profile,email,user_friends'
});
} else if (loginState === 'connected') {
loginToApp(redirectUrl, object);
}
}
// Connect to local app
function loginToApp(redirectUrl, object) {
// Connect to local app with facebook informations
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<a onclick="rateApic(this);" data-entry="42" href="#">Like</a>
Facebook says it's not a bug (it's for security reasons) and they won't fix it so...
This is what I did :
if (loginState === 'unknown' || loginState === "not_authorized" || loginState == undefined) {
FB.login(function(response) {
if (response.status === 'connected') {
loginToApp(redirectUrl, object);
};
}, {
scope: rights
});
if (checkLoginState() === 'unknown') {
// Redirect to the login page
$.ajax({
url: '/GetFacebookAppId',
type: 'POST',
dataType: 'json',
success: function(result, status) {
window.location.href = 'https://www.facebook.com/dialog/oauth?' + 'client_id=' + result.appId + '&redirect_uri=' + redirectUrl + '&scope=' + rights;
},
error: function(result, status, error) {},
complete: function(result, status) {}
});
}
}
So anytime the FB.login is not working and the FB.getLoginStatus returns "unknown", I redirect the user to the login page.
Searching for an answer for this question
I got as a result that follwing code works fine:
xhr = new XMLHttpRequest();
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
response = JSON.parse(xhr.responseText);
if(typeof response =='object') {
$('#modal-spinner-seo-update').hide('slow');
jQuery.each(result, function(field, message) {
$('#seo-'+field).next('div.error-message').html(message).fadeIn('fast');
});
} else {
$('#modal-spinner-seo-update').hide('slow', function() {
$("#seo-widget-message-success").fadeIn('slow').delay(2000).fadeOut('slow');
});
}
return false;
}
};
xhr.open('GET','/metas/saveMetas?model='+model+'&f_key='+f_key+'&pagetitle='+pagetitle+'&keywords='+keywords+'&description='+description+'&niceurl='+niceurl, true );
xhr.send();
but this jQuery Version does not work.
So can anyone spot the mistake? Is there any? The jQuery AJAX version works fine on my localhost but the server it does not, but return an 403 Forbidden Error. It is a cakePHP project.
So I hope someone ca tell me whats wrong or what setting is missing.
$.ajax({
url: '/metas/saveMetas',
data: {
"model": model,
"f_key": f_key,
"pagetitle": pagetitle,
"keywords": keywords,
"description": description,
"niceurl": niceurl
},
dataType: 'json',
complete: function(){
return false;
},
success: function(result) {
if(typeof result =='object') {
$('#modal-spinner-seo-update').hide('slow');
jQuery.each(result, function(field, message) {
$('#seo-'+field).next('div.error-message').html(message).fadeIn('fast');
});
} else {
$('#modal-spinner-seo-update').hide('slow', function() {
$("#seo-widget-message-success").fadeIn('slow').delay(2000).fadeOut('slow');
});
}
return false;
}
});
Something else to think about, in addition to the dataType:
Since it's returning a 403 error, have you added the 'saveMetas' method in the $this->Auth->allow() method in the beforeFilter() of 'MetasController' of your CakePHP project?
class MetasController extends AppController {
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('saveMetas');
}
...
...
}
EDIT:
Since you said you have done this, do you have $this->autoRender = false; and $this->layout = 'ajax'; as well in your saveMetas function?
Lastly, since you can visit that page directly, do a pr( $this->request ) after the initial function call and visit the page without AJAX to see what it is telling you. 403 forbidden tells me it's a permissions issue.