chrome active tab url passing to php file - javascript

I am making extension for Chrome and I need to pass the url of active tab to file with php code. My manifest.json code:
{ "name": "demo",
"version": "1.0",
"manifest_version": 2,
"description": "Making your first Google Chrome extension.",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "chrome.html"
},
"permissions": [
"http://www.mysite.com/",
"tabs"
]
}
and AJAX code:
window.onload = function() {
var XHR = new XMLHttpRequest;
chrome.tabs.query({active:true,currentWindow:true},
function(tab){tabUrl = tab.url;});
XHR.open('GET', 'http://www.mysite.com/chrome/chrome.php?tab='+tabUrl+'', true);
XHR.onreadystatechange = function () {
if (4 == this.readyState) {
var status = this.status;
if (400 > status) {
var responseText = this.responseText;
if (responseText) {
document.getElementById('resultado').innerHTML = responseText;
}
}
}
};
XHR.send();
}
Thanks for help.

I think you should do it like this, because in your code, since tabs.query is asynchronous, when XHR.send(); gets executed tabUrl isn't set yet.
window.onload = function() {
var XHR = new XMLHttpRequest;
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tab) {
tabUrl = tab.url;
XHR.open('GET', 'http://www.mysite.com/chrome/chrome.php?tab=' + tabUrl + '', true);
XHR.onreadystatechange = function() {
if(4 == this.readyState) {
var status = this.status;
if(400 > status) {
var responseText = this.responseText;
if(responseText) {
document.getElementById('resultado').innerHTML = responseText;
}
}
}
};
XHR.send();
});
}

Related

Handsontable autosave - ajax not defined

I copied the code from Handsontable official documentation, into a JSFiddle. This is handsontable 0.34.5.
I am getting an error in chrome console:
"ajax is not defined".
Code as follows, pre-loaded with handsontable.full.min.js and handsontable.full.min.css
HTML:
<div class="ajax-container">
<div class="controls">
<button name="load" id="load" class="intext-btn">Load</button>
<button name="save" id="save" class="intext-btn">Save</button>
<label>
<input type="checkbox" name="autosave" id="autosave" checked="checked" autocomplete="off">Autosave</label>
</div>
<pre id="example1console" class="console">Click "Load" to load data from server</pre>
<div id="example1" class="hot handsontable"></div>
</div>
Script:
var
$$ = function(id) {
return document.getElementById(id);
},
container = $$('example1'),
exampleConsole = $$('example1console'),
autosave = $$('autosave'),
load = $$('load'),
save = $$('save'),
autosaveNotification,
hot;
hot = new Handsontable(container, {
startRows: 8,
startCols: 6,
rowHeaders: true,
colHeaders: true,
afterChange: function(change, source) {
if (source === 'loadData') {
return; //don't save this change
}
if (!autosave.checked) {
return;
}
clearTimeout(autosaveNotification);
ajax('scripts/json/save.json', 'GET', JSON.stringify({
data: change
}), function(data) {
exampleConsole.innerText = 'Autosaved (' + change.length + ' ' + 'cell' + (change.length > 1 ? 's' : '') + ')';
autosaveNotification = setTimeout(function() {
exampleConsole.innerText = 'Changes will be autosaved';
}, 1000);
});
}
});
Handsontable.dom.addEvent(load, 'click', function() {
ajax('scripts/json/load.json', 'GET', '', function(res) {
var data = JSON.parse(res.response);
hot.loadData(data.data);
exampleConsole.innerText = 'Data loaded';
});
});
Handsontable.dom.addEvent(save, 'click', function() {
// save all cell's data
ajax('scripts/json/save.json', 'GET', JSON.stringify({
data: hot.getData()
}), function(res) {
var response = JSON.parse(res.response);
if (response.result === 'ok') {
exampleConsole.innerText = 'Data saved';
} else {
exampleConsole.innerText = 'Save error';
}
});
});
Handsontable.dom.addEvent(autosave, 'click', function() {
if (autosave.checked) {
exampleConsole.innerText = 'Changes will be autosaved';
} else {
exampleConsole.innerText = 'Changes will not be autosaved';
}
});
The code of the ajax function they are using is rather simple, is just a wrapper around XMLHttpRequest.
NOTE: I got it by just executing ajax.toString() via devtools on their docs page. It isn't referencing external functions, so it will work as is.
function ajax(url, method, params, callback) {
var obj;
try {
obj = new XMLHttpRequest();
} catch (e) {
try {
obj = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
obj = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support Ajax.");
return false;
}
}
}
obj.onreadystatechange = function () {
if (obj.readyState == 4) {
callback(obj);
}
};
obj.open(method, url, true);
obj.setRequestHeader("X-Requested-With", "XMLHttpRequest");
obj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
obj.send(params);
return obj;
}

The response text of Symfony StreamedResponse gets concatenated when using AJAX XMLHttpRequest

I have the controller below which returns Line 1 (as response) as soon as the endpoint is called. Two seconds later it returns Line 2. This is fine when I directly access URL http://ajax.dev/app_dev.php/v2 so this proves that the endpoint works as expected.
/**
* #Method({"GET"})
* #Route("/v2", name="default_v2")
*
* #return Response
*/
public function v2Action()
{
$response = new StreamedResponse();
$response->setCallback(function () {
echo 'Line 1';
ob_flush();
flush();
sleep(2);
echo 'Line 2';
ob_flush();
flush();
});
return $response;
}
When I use AJAX to call the same endpoint, the first response is fine which is response: "Line 1". However, the second one is response: "Line 1Line2" so it is combined. What should I do in order to get response: "Line2" as the second response? See console log below.
XMLHttpRequest { onreadystatechange: xhr.onreadystatechange(), readyState: 3,
timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload,
responseURL: "http://ajax.dev/app_dev.php/v2", status: 200,
statusText: "OK", responseType: "", response: "Line 1" }
XMLHttpRequest { onreadystatechange: xhr.onreadystatechange(), readyState: 3,
timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload,
responseURL: "http://ajax.dev/app_dev.php/v2", status: 200,
statusText: "OK", responseType: "", response: "Line 1Line2" }
Complete
This is the AJAX I am using.
$(document).ready(function () {
$('button').click(function () {
xhr = new XMLHttpRequest();
xhr.open("GET", 'http://ajax.dev/app_dev.php/v2', true);
xhr.onprogress = function(e) {
console.log(e.currentTarget);
};
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log("Complete");
}
};
xhr.send();
});
});
This can only be a temporary solution for now because every single response adds up and become a massive response rather than having a clean response.
e.g.
Response 1: Hello
Response 2: World
Response 3: Bye
XMLHttpRequest e.currentTarget property would contain:
Hello
HelloWorld
HelloWorldBye
The responseText property of XMLHttpRequest always contains the content that's been flushed out of the server, even when the connection's still open. So the browser can run a periodic check, e.g. to see if its length has changed.
For the time being I'll use code below but if I can find a better solution, I'll post it.
<script>
$(document).ready(function () {
$('button').click(function () {
xhr = new XMLHttpRequest();
xhr.open('GET', 'http://ajax.dev/app_dev.php/v2', true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onprogress = function(e) {
var response = e.currentTarget.response;
var output = typeof lastResponseLength === typeof undefined
? response
: response.substring(lastResponseLength);
lastResponseLength = response.length;
console.log(output);
};
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log('Complete');
}
};
xhr.send();
});
});
</script>

Unable to send cross-domain request in `Firefox` extension

I am trying to access cross-domain data by using jsonp or XMLHttpRequest with GET method. My Code:
XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://example.com/ajax.php?code=BSE", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
alert(xhr.responseText);
}
xhr.send();
JsonP
$.ajax({
type: 'GET',
url: "http://example.com/ajax.php?code=BSE",
dataType: "jsonp",
jsonpCallback: "jsonp_callback",
crossDomain: true,
success: function(res){
console.log(res);
}
});
Both methods having same behavior. Whenever i am sending request its just keep loading (even i am not sure its sending request or not) and do nothing.
And my php code:
PHP Code:
header('content-type: application/json; charset=utf-8');
$dts=array('value'=>'123');
echo $_GET['jsonp_callback'] . '('.json_encode($dts).')';
The XMLHttpRequest will work just fine, no need for jsonp. In your manifest.json, make sure you request permissions for the domain you are posting to -- Chrome doesn't require permissions for XHR, but Firefox does. This error manifests in Firefox as a http code 404 in the XHR, but no activity in the network panel. If you get a http code 0, you have CORS or mixed content security issues as well.
{
"manifest_version": 2,
"name": "web extension",
"version": "1",
"permissions": [
"http://example.com/"
],
"content_scripts": [
{
// ...
}
]
}
Try using new XDomainRequest() in your xhr request. XDomainRequest is an implementation of HTTP access control (CORS).
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Most browsers.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// IE8 & IE9
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
};
var url = 'http://example.com/ajax.php?code=BSE';
var method = 'GET';
var xhr = createCORSRequest(method, url);
xhr.onload = function() {
// Success code goes here.
};
xhr.onerror = function() {
// Error code goes here.
};
xhr.setRequestHeader('content-type', 'application/json; charset=utf-8');
xhr.send();

SyntaxError: JSON Parse error: Unexpected EOF using TVJS Framework

I am building a TVML application for Apple TV. When I run this code to make a request to a remote server I get this error: SyntaxError: JSON Parse error: Unexpected EOF. I am trying to run the code from the application.js file and populate the applications inital view. Any help is appreciated.
loadData("https:/xxx.xxx.net")
function loadData(url) {
var xhr;
var jsonData;
xhr = new XMLHttpRequest();
xhr.responseType = "json";
xhr.onreadystatechange = function() {
if (xhr.status == 200) {
jsonData = JSON.parse(xhr.responseText);
console.log(jsonData);
};
};
xhr.open("GET", url, true);
xhr.send();
if (jsonData != undefined) { return jsonData }
};
Other devices like Roku use the same api and function correctly.
{
"playlists": [
{
"id": 8,
"title": "test",
"description": "new playlist test",
"cover_url": "http://598-1446309178.png"
},
{
"id": 9,
"title": "test1",
"description": "lives",
"cover_url": "http://754-1446309324.jpg"
},
{
"id": 10,
"title": "test2",
"description": "video games",
"cover_url": "http://6173-1446310649.jpg"
},
{
"id": 11,
"title": "test4",
"description": "little",
"cover_url": "http://dd6-1446312075.jpg"
}
]
}
You can debug your app using Safari.
Once your app is running, choose "Develop / Simulator / {your app}".
That part of your code looks OK, but check what xhr.responseText is, it may return empty.
Your other error is that you are making an async request when you use "true" below:
xhr.open("GET", url, true);
You need to supply a callback to your function and use that callback.
I am using error first callback style.
function loadData(url, callback) {
var xhr;
var jsonData;
xhr = new XMLHttpRequest();
xhr.responseType = "json";
xhr.onreadystatechange = function() {
if (xhr.status == 200) {
try{
jsonData = JSON.parse(xhr.responseText);
} catch(e) {
return callback('json parsing error');
}
callback(null, jsonData);
console.log(jsonData);
};
};
xhr.open("GET", url, true);
xhr.send();
};

Accessing API from Chrome extension

I have a website which I have added as an extension in Google Chrome. What I need is that I have to access a server file from the extension. And I need is that whatever the server file outputs, I need to access the output in the extension.
Here is my 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"
},
"externally_connectable": {
"matches": ["http://calpinemate.com/"]
}
}
Here is my background.js
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.tabs.create({ "url": "http://calpinemate.com" });
});
Now what I need is that I have a server file (index.php) which outputs 1. Now what I need is that I want to get this 1 in extension. That is whatever the file outputs I want that output in extension. How can I do that?
Here is my index.php
<?php echo 1 ;?>
I tried this.But still it is only working on Onclick event.Please check my code.
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();
}
});
}
if (chrome.runtime && chrome.runtime.onStartup) {
chrome.runtime.onStartup.addListener(function() {
updateIcon();
});
} else {
chrome.windows.onCreated.addListener(function() {
updateIcon();
});
}
function updateIcon(){
var req = new XMLHttpRequest();
req.addEventListener("readystatechange", function() {
if (req.readyState == 4) {
if (req.status == 200) {
localStorage.item=req.responseText;
//alert(localStorage.item);
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:""});
}
// We received the data
//alert("Data: " + req.responseText);
} else {
// Handle the error
alert("ERROR: status code " + req.status);
}
}
});
req.open("GET", "http://blog.calpinetech.com/test/index.php", true);
req.send(null);
}
First request permission to access your server:
// In manifest.json
...
permissions: [
...
"*://calpinemate.com/index.php"
],
Then use AJAX to access the data:
var req = new XMLHttpRequest();
req.addEventListener("readystatechange", function() {
if (req.readyState == 4) {
if (req.status == 200) {
// We received the data
alert("Data: " + req.responseText);
} else {
// Handle the error
alert("ERROR: status code " + req.status);
}
}
});
req.open("GET", "https://calpinemate.com/index.php", true);
req.send(null);

Categories

Resources