I am working on a browser extension using crossrider. I need to send some data from popup to extension.js
My code of popup
<!DOCTYPE html>
<html>
<head>
<!-- This meta tag is relevant only for IE -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script type="text/javascript">
/************************************************************************************
This is your Popup Code. The crossriderMain() code block will be run
every time the popup is opened.
For more information, see:
http://docs.crossrider.com/#!/api/appAPI.browserAction-method-setPopup
*************************************************************************************/
function crossriderMain($) {
// var to store active tab's URL
var activeTabUrl = null;
// Message listener for response from active tab
appAPI.message.addListener(function(msg) {
if (msg.type === 'active-tab-url') activeTabUrl = msg.url;
});
// Request URL from active tab
appAPI.message.toActiveTab({type: 'active-tab-url'});
alert(activeTabUrl);
// THE REST OF YOUR CODE
}
</script>
</head>
<body>
Hello World
</body>
</html>
Code of Extension.js
appAPI.ready(function($) {
// Message listener
appAPI.message.addListener(function(msg) {
if (msg.type === 'active-tab-url')
// Send active tab's URL to popup
appAPI.message.toPopup({
type: 'active-tab-url',
url:encodeURIComponent(location.href)
});
});
// THE REST OF YOUR CODE
});
The value of activeTabUrl is not getting updated. It gives NULL value.
P.S : I am able to communicate between background.js and popup. But for some reason appAPI.message.toActiveTab function is not working for me. Where I am doing the mistake?
Background.js (Edit)
var tabUrl='';
/* appAPI.tabs.getActive(function(tabInfo) {
tabUrl = tabInfo.tabUrl;
}); */
appAPI.message.addListener(function(msg) {
appAPI.tabs.getActive(function(tabInfo) {
tabUrl = tabInfo.tabUrl;
});
var dataString = '{"url":"'+tabUrl+'","access":"'+msg.access+'","toread":"'+msg.toread+'","comment":"'+msg.comment+'"}';
alert(dataString);
appAPI.request.post({
url: 'REST API URL',
postData: dataString,
onSuccess: function(response, additionalInfo) {
var details = {};
details.response = response;
appAPI.message.toPopup({
response:response
});
},
onFailure: function(httpCode) {
// alert('POST:: Request failed. HTTP Code: ' + httpCode);
}
});
});
Working code of Background.js
appAPI.message.addListener(function(msg) {
appAPI.tabs.getActive(function(tabInfo) {
var dataString = '{"url":"'+tabInfo.tabUrl+'","access":"'+msg.access+'","toread":"'+msg.toread+'","comment":"'+msg.comment+'"}';
// alert(dataString);
appAPI.request.post({
url: 'http://fostergem.com/api/bookmark',
postData: dataString,
onSuccess: function(response, additionalInfo) {
var details = {};
details.response = response;
appAPI.message.toPopup({
response:response
});
},
onFailure: function(httpCode) {
// alert('POST:: Request failed. HTTP Code: ' + httpCode);
}
});
});
});
In this code sample, the activeTabUrl variable is only set once a response is received from the extension.js file since the messaging is asynchronous by design. Hence, when calling alert(activeTabUrl); in the code, the message has not yet been received back fro the extension.js code thus the value is still null as it was initialized.
To use the activeTabUrl variable you must wait for the mesage from the extension.js file, and hence you should place the code using the variable in the callback of the message listener, preferably as a function. Also note that using an alert in the popup code causes the popup to close and should hence not be used in the popup scope.
I tested the following popup code, which does away with the variable to avoid confusion and passes the active tab URL as a parameter to the function called in the message listener, and it worked as expected:
function crossriderMain($) {
// Message listener for response from active tab
appAPI.message.addListener(function(msg) {
if (msg.type === 'active-tab-url') ShowPageUrl(msg.url);
});
function ShowPageUrl(url) {
$('#page-url').html('<b>Page URL</b>: ' + url);
}
// Request URL from active tab
appAPI.message.toActiveTab({type: 'active-tab-url'});
//alert(activeTabUrl);
// THE REST OF YOUR CODE
}
[Disclaimer: I am a Crossrider employee]
Related
I am working on a project where I need to capture the browser close event (unload or beforeunload). For that I have tried the code below but it's not working.
The code is working only if I open the browser console window (maybe just for a second) but it is required otherwise it's not working.
Example
$(window).on('beforeunload', function(e) {
$.ajax({
type: "POST",
url: "url",
data : {'value' : 1},
dataType:'json'
});
return false;
});
The beacon API is meant specifically for that. Sending a request as the page is unloading. https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API
Beacon requests use the HTTP POST method and requests typically do not require a response. Requests are guaranteed to be initiated before a page is unloaded and they are run to completion, without requiring a blocking request (for example XMLHttpRequest).
window.onunload = function analytics(event) {
if (!navigator.sendBeacon) return;
var url = "https://example.com/analytics";
// Create the data to send
var data = "state=" + event.type + "&location=" + location.href;
// Send the beacon
var status = navigator.sendBeacon(url, data);
// Log the data and result
console.log("sendBeacon: URL = ", url, "; data = ", data, "; status = ", status);
};
I'm using a script to extract data from google search console in a sheet.
I built a sidebar to chose on which website the user want to analyse his data.
For that i have a function that can list all sites link to the google account, but i have an error when i try to execute this function in my html file.
I use withSuccessHandler(function) method which sets a callback function to run if the server-side function returns successfully. (i have a OAuth2.0.gs file where is my getService function.
The error is "service.hasAccess is not a function at listAccountSites" where listAccountSites is my function. Here's an extract of my html file:
<script src="OAuth2.0.gs"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(function() {
var liste = google.script.run.withSuccessHandler(listAccountSites)
.getService();
console.log(liste);
});
function listAccountSites(service){
if (service.hasAccess()) {
var apiURL = "https://www.googleapis.com/webmasters/v3/sites";
var headers = {
"Authorization": "Bearer " + getService().getAccessToken()
};
var options = {
"headers": headers,
"method" : "GET",
"muteHttpExceptions": true
};
var response = UrlFetchApp.fetch(apiURL, options);
var json = JSON.parse(response.getContentText());
Logger.log(json)
console.log('if')
var URLs = []
for (var i in json.siteEntry) {
URLs.push([json.siteEntry[i].siteUrl, json.siteEntry[i].permissionLevel]);
}
/*
newdoc.getRange(1,1).setValue('Sites');
newdoc.getRange(1,3).setValue('URL du site à analyser');
newdoc.getRange(2,1,URLs.length,1).setValues(URLs);
*/
console.log(URLs);
} else {
console.log('else')
var authorizationUrl = service.getAuthorizationUrl();
Logger.log('Open the following URL and re-run the script: %s', authorizationUrl);
Browser.msgBox('Open the following URL and re-run the script: ' + authorizationUrl);
}
return URLs;
}
</script>
i found the solution.
Jquery is useless here, you just have to use google.script.run.yourfunction() to run your gs. function on your html sidebar.
I am developing a browser extension using crossrider.
I have added a context menu (background.js)
var ContextData;
appAPI.contextMenu.add("key1", "Send Data To Server", function (data) {
var ContextData = 'pageUrl: ' + data.pageUrl + '\r\n' +
'linkUrl: ' + data.linkUrl + '\r\n' +
'selectedText:' + data.selectedText + '\r\n' +
'srcUrl:' + data.srcUrl;
}, ["all"]);
On user click I want to send ContextData to extension.js. At extension.js some function will receive the data and send it to my server (A Rest API which will accept the data).
To send data to the server I have tested this and it works fine (code sample in extension.js)
appAPI.ready(function($) {
var dataToSend =="test data";
appAPI.request.post({
url: 'REST API URL',
postData: dataToSend,
onSuccess: function(response, additionalInfo) {
var details = {};
details.response = response;
},
onFailure: function(httpCode) {
// alert('POST:: Request failed. HTTP Code: ' + httpCode);
}
});
});
How can I write a function to accept ContextData from background.js and assign it to dataToSend in extension.js?
#Neel If I understand your requirements correctly, #Rob is essentially correct though a little clarification may help
By design/architecture, the extension.js code runs on each HTML page i.e. a separate extension.js instance is run for each URL that loads. In contrast, the context menu runs at the browser level (not HTML page) and is hence correctly coded in background.js file. However, the background.js code does not have direct access to the extension.js instance code running on the HTML page in the active tab and must therefore communicate the data via messaging. (For more information about scopes, see Scopes Overview)
Obviously, a user clicks the context menu item on the active tab (i.e. the page showing the HTML page being viewed); hence, once the ContextData string is created, you can use appAPI.message.toActiveTab to send the string to the extension.js instance running on the page/tab where the the context menu item was clicked.
This being the case, using your code example you can achieve this goal as follows:
background.js:
appAPI.ready(function($) {
var ContextData;
appAPI.contextMenu.add("key1", "Send Data To Server", function (data) {
var ContextData = 'pageUrl: ' + data.pageUrl + '\r\n' +
'linkUrl: ' + data.linkUrl + '\r\n' +
'selectedText:' + data.selectedText + '\r\n' +
'srcUrl:' + data.srcUrl;
appAPI.message.toActiveTab({type:'dataToSend', data: ContextData});
}, ["all"]);
});
extension.js:
appAPI.ready(function($) {
var dataToSend =="test data";
appAPI.message.addListener(function(msg) {
if (msg.type === 'dataToSend') {
appAPI.request.post({
url: 'REST API URL',
postData: dataToSend,
onSuccess: function(response, additionalInfo) {
var details = {};
details.response = response;
},
onFailure: function(httpCode) {
// alert('POST:: Request failed. HTTP Code: ' + httpCode);
}
});
}
});
});
[Disclaimer: I am a Crossrider employee]
I'm submitting an Ajax request from an https page to an https page. In all other browsers, this goes through instantly, but in Chrome it hangs for a long time (usually about 40 seconds).
What could be causing this? how do I fix it?
EXAMPLE JQUERY CODE THAT ALSO CAUSES THE HANG
<html>
<head>
<script type="text/javascript" src="jquery-1-9-1.js"></script>
</head>
<body>
<br/>
<a onclick="doit()">go</a>
<script>
function doit()
{
var myData = { "key": "value" };
$.ajax({
url: "myhandlepage.php",
data: myData,
dataType: 'json',
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
success: function (data) { alert("OK = " + data.eric); },
error: function (data, status) { alert("FAILED:" + status); }
});
}
</script>
</body>
</html>
EXAMPLE CODE
//Create browser-compliant request object
if( typeof XMLHttpRequest === "undefined" ) XMLHttpRequest = function()
{
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
throw new Error( "This browser does not support XMLHttpRequest." );
};
//Create object
var ajax = new XMLHttpRequest();
//We need to open the object
ajax.open( "post", "/myhandlepage.php", true );
//Now set the callback
ajax.onreadystatechange = function()
{
//elided, but doesn't matter, I can see the 40+ second delay in chrome developer tools
}.bind( this );
//Send the request
ajax.send( mycontent );
For clarification: no errors are shown in Chrome's developer tools.
EDIT: It appears that this issue only happens on the first request for a tab/page in Chrome. All ajax requests in that same tab/page seem to go through instantly after the first lagging request.
MORE INFO
Looking in chrome:net-internals/#events on the hanging request only, in the middle of all the requests, I see this:
t=1360622033867 [st= 4] HTTP_STREAM_PARSER_READ_HEADERS [dt=38643]
--> net_error = -100 (ERR_CONNECTION_CLOSED)
Then it sends the entire request again, and that second time it goes through instantly. What could be causing this first failed request? It occurs every time I do the request for the first time to that URL since opening the browser.
I have a link: Hello.
When someone clicks the link I'd like to check via JavaScript if the page the href-attribute points to exists or not. If the page exists the browser redirects to that page ("www.example.com" in this example) but if the page doesn't exist the browser should redirect to another URL.
It depends on whether the page exists on the same domain or not. If you're trying to determine if a page on an external domain exists, it won't work – browser security prevents cross-domain calls (the same-origin policy).
If it is on the same domain however, you can use jQuery like Buh Buh suggested. Although I'd recommend doing a HEAD-request instead of the GET-request the default $.ajax() method does – the $.ajax() method will download the entire page. Doing a HEAD request will only return the headers and indicate whether the page exists (response codes 200 - 299) or not (response codes 400 - 499). Example:
$.ajax({
type: 'HEAD',
url: 'http://yoursite.com/page.html',
success: function() {
// page exists
},
error: function() {
// page does not exist
}
});
See also: http://api.jquery.com/jQuery.ajax/
A pretty good work around is to proxy. If you don't have access to a server side you can use YQL. Visit: http://developer.yahoo.com/yql/console/
From there you can do something like: select * from htmlstring where url="http://google.com". You can use the "REST query" they have on that page as a starting point for your code.
Here's some code that would accept a full URL and use YQL to detect if that page exists:
function isURLReal(fullyQualifiedURL) {
var URL = encodeURIComponent(fullyQualifiedURL),
dfd = $.Deferred(),
checkURLPromise = $.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20htmlstring%20where%20url%3D%22' + URL + '%22&format=json');
checkURLPromise
.done(function(response) {
// results should be null if the page 404s or the domain doesn't work
if (response.query.results) {
dfd.resolve(true);
} else {
dfd.reject(false);
}
})
.fail(function() {
dfd.reject('failed');
});
return dfd.promise();
}
// usage
isURLReal('http://google.com')
.done(function(result) {
// yes, or request succeded
})
.fail(function(result) {
// no, or request failed
});
Update August 2nd, 2017
It looks like Yahoo deprecated "select * from html", although "select * from htmlstring" does work.
Based on the documentation for XMLHttpRequest:
function returnStatus(req, status) {
//console.log(req);
if(status == 200) {
console.log("The url is available");
// send an event
}
else {
console.log("The url returned status code " + status);
// send a different event
}
}
function fetchStatus(address) {
var client = new XMLHttpRequest();
client.onreadystatechange = function() {
// in case of network errors this might not give reliable results
if(this.readyState == 4)
returnStatus(this, this.status);
}
client.open("HEAD", address);
client.send();
}
fetchStatus("/");
This will however only work for URLs within the same domain as the current URL. Do you want to be able to ping external services? If so, you could create a simple script on the server which does your job for you, and use javascript to call it.
If it is in the same domain, you can make a head request with the xmlhttprequest object [ajax] and check the status code.
If it is in another domain, make an xmlhttprequest to the server and have it make the call to see if it is up.
why not just create a custom 404 handler on the web server? this is probably the more "good-bear" way to do this.
$.ajax({
url: "http://something/whatever.docx",
method: "HEAD",
statusCode: {
404: function () {
alert('not found');
},
200: function() {
alert("foundfile exists");
}
}
});
If you are happy to use jQuery you could do something like this.
When the page loads make an ajax call for each link. Then just replace the href of all the links which fail.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
<!--
$.fn.checkPageExists = function(defaultUrl){
$.each(this, function(){
var $link = $(this);
$.ajax({
url: $link.attr("href"),
error: function(){
$link.attr("href", defaultUrl);
}
});
});
};
$(document).ready(function(){
$("a").checkPageExists("default.html");
});
//-->
</script>
You won't be able to use an ajax call to ping the website because of same-origin policy.
The best way to do it is to use an image and if you know the website you are calling has a favicon or some sort of icon to grab, you can just use an html image tag and use the onerror event.
Example:
function pingImgOnWebsite(url) {
var img = document.createElement('img');
img.style.visibility = 'hidden';
img.style.position = 'fixed';
img.src = url;
img.onerror = continueBtn; // What to do on error function
document.body.appendChild(img);
}
Another way to do this is is with PHP.
You could add
<?php
if (file_exists('/index.php'))
{
$url = '/index.php';
} else {
$url = '/notindex.php';
}
?>
And then
<a href="<?php echo $url; ?>Link</a>