I'm currently writing an extension using Crossrider, and I need to load an image directly using the URL for doing some image processing on it. However, the onload event doesn't seem to be firing at all.
Am I doing something wrong or is it even possible to do that in a browser extension?
Here is the relevant piece of code:
var imga = document.createElement('img');
imga.src = obj.attr('href'); // URL of the image
imga.style.display = 'none';
imga.onload = function() {
alert('Image loaded');
var imgData = getImageData(imga, 0, imga.height - 3);
alert('Got Image data');
};
EDIT
Here is the full code
function readImage(obj)
{
console.log('Reading');
relayReadImage(obj.attr('href'));
}
function relayReadImage(link)
{
var dateObj = new Date();
var newlink = link + "?t=" + dateObj.getTime();
console.log(newlink);
appAPI.request.get(
{
url: newlink,
onSuccess: function(response, additionalInfo) {
console.log(response);
},
onFailure: function(httpCode) {
alert('GET:: Request failed. HTTP Code: ' + httpCode);
}
});
}
I'm a Crossrider employee and would be happy to help you. If I understand correctly, you are attempting to use the URL (href) of an object in a page's dom (obj.attr('href')) to load the image into a variable in the extension. You can achieve this using our cross-browser appAPI.request.get method in your extension.js file, as follows:
appAPI.ready(function($) {
appAPI.request.get({
url: obj.attr('href'),
onSuccess: function(response) {
var imgData = response;
console.log(imgData);
}
});
});
However, if I've misunderstood your question, please can you clarify the following:
What is the obj object is?
What are you trying to achieve, and in which context (in the Extension or on the Page)?
Related
If there is an img tag in a page whose final image it displays comes after a 302 redirect, is there a way with javascript to obtain what that final URL is after the redirect? Using javascript on img.src just gets the first URL (what's in the page), not what it was redirected to.
Here's a jsfiddle illustration: http://jsfiddle.net/jfriend00/Zp4zG/
No, this is not possible. src is an attribute and it does not change.
I know this question is old, and was already marked answered, but another question that I was trying to answer was marked as a duplicate of this, and I don't see any indication in any of the existing answers that you can get the true URL via the HTTP header. A simple example (assuming a single image tag on your page) would be something like this...
var req = new XMLHttpRequest();
req.onreadystatechange=function() {
if (req.readyState===4) {// && req.status===200) {
alert("actual url: " + req.responseURL);
}
}
req.open('GET', $('img').prop('src'), true);
req.send();
If you are open to using third party proxy this can be done. Obviously not a javascript solution This one uses the proxy service from cors-anywhere.herokuapp.com. Just adding this solution for people who are open to proxies and reluctant to implement this in backend.
Here is a fork of the original fiddle
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
//options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});
$.ajax({
type: 'HEAD', //'GET'
url:document.getElementById("testImage").src,
success: function(data, textStatus, request){
alert(request.getResponseHeader('X-Final-Url'));
},
error: function (request, textStatus, errorThrown) {
alert(request.getResponseHeader('X-Final-Url'));
}
});
based on http://jsfiddle.net/jfriend00/Zp4zG, this snippets works in Firefox 17.0:
alert(document.getElementById("testImage").baseURI)
It doesn't work in Chrome. Not tested anything else-
Here is a workaround that I found out. But it works only if the image on the same domain otherwise you will get an empty string:
var img = document.getElementById("img");
getSrc(img.getAttribute("src"), function (realSrc) {
alert("Real src is: " + realSrc);
});
function getSrc(src, cb) {
var iframe = document.createElement("iframe"),
b = document.getElementsByTagName("body")[0];
iframe.src = src;
iframe.className = "hidden";
iframe.onload = function () {
var val;
try {
val = this.contentWindow.location.href;
} catch (e) {
val = "";
}
if (cb) {
cb(val);
}
b.removeChild(this);
};
b.appendChild(iframe);
}
http://jsfiddle.net/infous/53Layyhg/1/
I initialize Uploadify using the following code:
$('#file1').uploadifive({
'buttonClass': 'upload-btn',
'uploadScript': '/Upload/',
'fileObjName': 'files',
'fileType': 'text/xml',
'formData': { 'uploadType': 'Crew' },
'onUploadComplete': function(file, data) {
var results = $.parseJSON(data);
if (results.error) {
var info = file.queueItem.find('span.fileinfo');
if (info) info.text(' - ' + results.error);
return;
}
window.location.href = '#Url.Content("~/Upload/Checkdata/")' + results.id;
}
});
This works, however I need to modify the formData property when a radio checkbox changes. So, I've tried this:
$('input[name=UploadType]:radio').change(function () {
$('#file1').uploadifive({ 'formData': this.value });
});
However, when that code runs, it breaks the Uploadify control (it now no longer uploads anywhere). I'm guessing because it completely re-initializes the control with all new settings.
How can I update just this one setting? I've read the Uploadify docs and none of them say anything about updating settings; just initializing and calling methods. Thanks!
I've figured out one solution, but not sure if it's the right way to do things (i.e., it might break in future versions of Uploadify).
Basically, it appears you can keep a reference to your configuration around, and update that object at any time:
var uploadifySettings = {
'buttonClass': 'upload-btn',
'uploadScript': '/Upload/',
'fileObjName': 'files',
'fileType': 'text/xml',
'formData': { 'uploadType': 'Crew' },
'onUploadComplete': function(file, data) {
var results = $.parseJSON(data);
if (results.error) {
var info = file.queueItem.find('span.fileinfo');
if (info) info.text(' - ' + results.error);
return;
}
window.location.href = '#Url.Content("~/Upload/Checkdata/")' + results.id;
}
}
$('input[name=UploadType]:radio').change(function () {
uploadifySettings.formData.uploadType = this.value;
});
$('#file1').uploadifive(uploadifySettings);
I am new to working with AJAX and have some experience with Java/Jquery. I have been looking around for an solution to my problem but i cant seem to find any.
I am trying to build a function in a webshop where the product will appear in a popup window instead of loading a new page.
I got it working by using this code:
$(".product-slot a").live('click', function() {
var myUrl = $(this).attr("href") + " #product-content";
$("#product-overlay-inner").load(myUrl, function() {
});
$("#product-overlay").fadeIn();
return false;
});
product-slot a = Link to the product in the category page.
product-content = the div i want to insert in the popup from the product page.
product-overlay-inner = The popup window.
product-overlay = The popup wrapper.
The problem that i now have is that my Javascript/Jquery isnt working in the productpopup. For example the lightbox for the product image or the button to add product to shoppingcart doesnt work. Is there anyway to make the javascript work inside the loaded content or to load javascript into the popup?
I hope you can understand what my problem is!
Thank you in advance!
EDIT: The platform im using has jquery-ui-1.7.2
I know this is an old thread but I've been working on a similar process with the same script loading problem and thought I'd share my version as another option.
I have a basic route handler for when a user clicks an anchor/button etc that I use to swap out the main content area of the site, in this example it's the ".page" class.
I then use a function to make an ajax call to get the html content as a partial, at the moment they are php files and they do some preliminary rendering server side to build the html but this isn't necessary.
The callback handles placing the new html and as I know what script I need I just append it to the bottom in a script tag created on the fly. If I have an error at the server I pass this back as content which may be just a key word that I can use to trigger a custom js method to print something more meaningful to the page.
here's a basic implementation based on the register route handler:
var register = function(){
$(".page").html("");
// use the getText ajax function to get the page content:
getText('partials/register.php', function(content) {
$(".page").html(content);
var script = document.createElement('script');
script.src = "js/register.js";
$(".page").append(script);
});
};
/******************************************
* Ajax helpers
******************************************/
// Issue a Http GET request for the contents of the specified Url.
// when the response arrives successfully, verify it's plain text
// and if so, pass it to the specified callback function
function getText(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url);
request.onreadystatechange = function() {
// if the request is complete and was successful -
if (request.readyState === 4 && request.status === 200) {
// check the content type:
var type = request.getResponseHeader("Content-Type");
if (type.match(/^text/)) {
callback(request.responseText);
}
}
};
// send it:
request.send(null); // nothing to send on GET requests.
}
I find this a good way to 'module-ize' my code into partial views and separated JavaScript files that can be swapped in/out of the page easily.
I will be working on a way to make this more dynamic and even cache these 'modules' for repeated use in an SPA scenario.
I'm relatively new to web dev so if you can see any problems with this or a safer/better way to do it I'm all ears :)
Yes you can load Javascript from a dynamic page, but not with load() as load strips any Javascript and inserts the raw HTML.
Solution: pull down raw page with a get and reattach any Javascript blocks.
Apologies that this is in Typescript, but you should get the idea (if anything, strongly-typed TypeScript is easier to read than plain Javascript):
_loadIntoPanel(panel: JQuery, url: string, callback?: { (): void; })
{
// Regular expression to match <script>...</script> block
var re = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;
var scripts: string = "";
var match;
// Do an async AJAX get
$.ajax({
url: url,
type: "get",
success: function (data: string, status: string, xhr)
{
while (match = re.exec(data))
{
if (match[1] != "")
{
// TODO: Any extra work here to eliminate existing scripts from being inserted
scripts += match[0];
}
}
// Replace the contents of the panel
//panel.html(data);
// If you only want part of the loaded view (assuming it is not a partial view)
// using something like
panel.html($(data).find('#product-content'));
// Add the scripts - will evaluate immediately - beware of any onload code
panel.append(scripts);
if (callback) { callback(); }
},
error: function (xhr, status, error)
{
alert(error);
}
});
}
Plain JQuery/Javascript version with hooks:
It will go something like:
var _loadFormIntoPanel = function (panel, url, callback) {
var that = this;
var re = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;
var scripts = "";
var match;
$.ajax({
url: url,
type: "get",
success: function (data, status, xhr) {
while(match = re.exec(data)) {
if(match[1] != "") {
// TODO: Any extra work here to eliminate existing scripts from being inserted
scripts += match[0];
}
}
panel.html(data);
panel.append(scripts);
if(callback) {
callback();
}
},
error: function (xhr, status, error) {
alert(error);
}
});
};
$(".product-slot a").live('click', function() {
var myUrl = $(this).attr("href") + " #product-content";
_loadFormIntoPanel($("#product-overlay-inner"), myUrl, function() {
// Now do extra stuff to loaded panel here
});
$("#product-overlay").fadeIn();
return false;
});
I have a simple regex function in jQuery to add an image tag to image URLs posted by users.
So that when a user posts for example www.example.com/image.jpg the image tag will be added so that user can see the image without clicking on the URL.
var hostname = window.location.hostname.replace(/\./g,'\\.');
var re = new RegExp('(http:\\/\\/[^' + hostname + ']\\S+[\\.jpeg|\\.png|\\.jpg|\\.gif])','g');
$(".texthold ").each(function() {
$(this).html($(this).html().replace(re, '<img src="$1" />'));
});
How can I check the file size of the image before allowing it to be viewable? So that if for example the image file size is bigger than 5MB the image will not be displayed and instead the URL will be shown.
var url = ...; // here you build URL from regexp result
var req = $.ajax({
type: "HEAD",
url: url,
success: function () {
if(req.getResponseHeader("Content-Length") < 5 * 1048576) // less than 5 MB?
; // render image tag
else
; // render URL as text
}
});
You will only be able to accomplish what you want if the server response for the images includes the appropriate Cross Origin Resource Sharing (CORS) header and a content-length header.
Additionally you will need to take into account the time required for the ajax requests to be fulfilled in your replacement loop.
Below is a jQuery (1.9.1) example which demonstrates what the final solution could look like. For it to work you will need to update the links to a server which returns proper CORS headers or disable security on your browser. The example is also on jsfiddle.
var largeImage = "http://eoimages.gsfc.nasa.gov/images/imagerecords/49000/49684/rikuzentakata_ast_2011073_lrg.jpg";
var smallImage = "http://eoimages.gsfc.nasa.gov/images/imagerecords/81000/81258/kamchatka_amo_2013143_tn.jpg";
var urls = [largeImage, smallImage];
var maxSize = 5000000;
$.each(urls, function(index, value) {
conditionalMarkupUpdater(value, maxSize);
});
var onShouldBeViewable = function () {
alert('This is a small image...Display it.');
};
var onShouldNotBeViewable = function () {
alert('This is a large image...Only provide the url.');
};
var onError = function() {
alert('There was an error...likely because of CORS issues see http://stackoverflow.com/questions/3102819/chrome-disable-same-origin-policy and http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/"');
};
function checkSize(url) {
var sizeChecker = new jQuery.Deferred();
var onSuccess = function (data, textStatus, jqXHR) {
var length = jqXHR.getResponseHeader('Content-Length');
if (!length) {
sizeChecker.reject("No size given");
} else {
sizeChecker.resolve(parseInt(length));
}
};
var onFailure = function (jqXHR, textStatus, errorThrown) {
sizeChecker.reject("Request failed");
};
$.when($.ajax({
type: "HEAD",
url: url
})).then(onSuccess, onFailure);
return sizeChecker.promise();
};
function conditionalMarkupUpdater(url, maxSize) {
$.when(checkSize(url)).then(
function (size) {
if (size <= maxSize) {
onShouldBeViewable();
} else {
onShouldNotBeViewable();
}
},
function (status) {
onError();
})
};
hoping some one can shed some light on my problem. Basicly I only want to execute a block of code if a certain DOM element exists. If it does I then perform a few bits and bobs and then call a function. However it complains that the function is not defined, suggesting that the function is not in scope. Below is the code :
$(document).ready(function ()
{
if ((document.getElementById("view<portlet:namespace/>:editSplash")!= null)) {
console.log("notifications scripted started");
// hide loading box/ notify on body load
$('.ajaxErrorBox').hide();
$('.loadingNotifications').hide();
$('.notifyWindow').hide();
getFeed();
// set up refresh button for reloading feed
$('.refreshFeed').click(function() {
$('.notifyWindow').hide();
$('.notifyWindow').empty();
console.log("notifications clicked");
getFeed();
});
// begin ajax call using jquery ajax object
function getFeed ()
{
$('.notifyWindow').empty();
console.log("ajax call for feed starting");
$.ajax ({
type: "GET",
url: "http://cw-pdevprt-05.tm-gnet.com:10040/notificationsweb/feed?username=uid=<%# taglib uri="/WEB-INF/tld/engine.tld" prefix="wps" %><wps:user attribute="uid"/>",
dataType: "text/xml",
timeout: 10000,
success: parseXml
});
};
// show loading box on start of ajax call
$('.notifyWindow').ajaxStart(function() {
$('.refreshFeed').hide("fast");
$('.notifyWindow').hide();
$('.ajaxErrorBox').hide();
$('.loadingNotifications').show("fast");
});
// hide loading box after ajax call has stopped
$('.notifyWindow').ajaxStop(function() {
$('.loadingNotifications').hide("slow");
$('.refreshFeed').show("fast");
});
$('.notifyWindow').ajaxError(function() {
$('.loadingNotifications').hide("slow");
$('.ajaxErrorBox').show("fast");
$('.refreshFeed').show("fast");
});
// parse the feed/ xml file and append results to notifications div
function parseXml (xml) {
console.log("xml parsing begining");
if (jQuery.browser.msie)
{
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.loadXML(xml);
xml = xmlDoc;
}
$(xml).find("entry").each(function()
{
var $item = $(this);
var title = $item.find("title").text();
var linkN = $item.find("link").attr("href");
var output = "<a href='" + linkN + "' target='_self'>" + title + "</a><br />";
$(".notifyWindow").append($(output)).show();
});
}
}
else {
console.log("notifications not available");
return false;
}
});
If the DOM element exists I then try and call the getFeed function "getFeed();" however it comes back undefined. If anyone could shed some light on this it would be greatly appreciated.
Thanks in advance
It seems that you're calling getFeed before it is defined. Try moving the if statement to after the function definition. Note that this behaviour is actually implementation specific, so some browsers may work this way and some may not.
Oh - And seriously? view<portlet:namespace/>:editSplash for an id?
Problem solved - I moved my functions outside of the if statement. We live and learn lol :-)