How to append GET parameter for every URL request from a browser? - html

For testing, I need to append "?testing=true" for every URL reference in my webpage.
For example, say webpage has an image "localhost/image/logo.png" I need to this should be converted to "localhost/image/logo.png?testing=true" when loaded on a browser.
I tried several plugins on firefox, which allows appending/modifying URL on submit, but my requirement is to change URL on load.

You might have some success with the Firefox Greasemonkey extension. You can use a script like this:
var parameter = '?testing=true'
for (var x = 0; x < document.images.length; x++) {
image = docuent.images[x];
image.src = image.src + parameter;
console.log(image.src);
}
for (x = 0; x < document.getElementsByTagName("link").length; x++) {
document.getElementsByTagName("link")[x].href = document.getElementsByTagName("link")[x].href + parameter;
}
It replaces all embedded images and stylesheets with the same files with "?testing=true" appended. However there are still requests to the original image before that.
Another option would be to use a local proxy such as Charles for URL rewriting.

Related

Google Chrome - download attribute of anchor tags

I've an extension which saves some files to the downloads folder. The code below is just for testing
//This lies in the background page of my extension
function fileTest(name) {
var a = document.createElement('a');
a.href = 'data:text/plain;base64,SGVsbG8gV29ybGQh'; //Hello World!
a.download = name + '.txt';
a.onclick = function (e) {console.log('[TEST] ' + name);return true;};
a.click();
}
window.onload = function() {
fileTest('test1');
fileTest('test12');
fileTest('test123');
}
only the first file "test1.txt" is saved to the disk, although the output of the console shows that there was 3 clicks
[TEST] test1
[TEST] test12
[TEST] test123
Is this an intentional limitation by the browser ? or there's something wrong with the code ?
When I run your code in a regular browsing session, I get a slide out notification (at the top of the window) that says
This site is attempting to download multiple files. Do you want to allow this?
So, yes, it is a security limitation of the browser to restrict downloads that are not user-initiated. You probably don't see the notification because the action is being performed by your background page.
The limitation seems to be one download per user action as demonstrated in this variant of your code:
window.onclick = function() {
fileTest('test1');
}
This will allow unlimited downloads, but only one download per click event.

HTML5 offline JSON doesn't work

I have a small HTML5 (using jQuery mobile) web app that caches its files to use them offline, however some parts don't seem to work once it's offline.
The files are cached OK (I can see them in the web inspector) but when I try to visit a page that uses jQuery to load a JSON file it doesn't load.
I tried creating an empty function to load the JSON files (when the index page is loaded) to see if that would help but it doesn't seem to make a difference.
Here's the function that doesn't want to work offline.
My question is: should it work offline or am I missing something?
// events page listing start
function listEvents(data){
$.getJSON('/files/events.json', {type: "json"},function (data) {
var output = '';
for (i in data)
{
var headline = data[i].headline;
var excerpt = data[i].rawtext;
output += '<div id="eventsList">';
output += '<h3>'+headline+'</h3>';
output += '<p>'+ excerpt +'<p>';
output += '</div>';
}
$("#eventsPageList").html(output).trigger("create");
});
}
I'm not really sure, if i'm right about this. But i think an ajax request will always fail when you are offline. It won't use the locally cached file. What you should try is, to cache the data in localStorage. When the ajax request fails, fallback to localStorage.
OK here's a version which seems to work, I read the json file and place it in localstorage then use the localstorage in the listEvents function.
When the page loads I call this function to add the json to localstorage
function cacheJson(data){
$.getJSON('/files/events.json',
{type: "json", cache: true},function (data) {
localStorage['events'] = JSON.stringify(data); });
}
Then this function to output the json (from localstorage) to the page, with an if else incase the localstorage doesn't contain the json.
function listEvents(data){
if (localStorage.getItem("events") === null) {
var output = '';
output += 'Sorry we have an error';
$("#eventsPageList").html(output).trigger("create");
}
else {
data = JSON.parse(localStorage['events']);
var output = '';
for (i in data)
{
var headline = data[i].headline;
var excerpt = data[i].rawtext;
output += '<div id="eventsList">';
output += '<h3>'+headline+'</h3>';
output += '<p>'+ excerpt +'<p>';
output += '</div>';
}
$("#eventsPageList").html(output).trigger("create");
}
}
It seems to work ok but am I missing something that could cause issues?
Is there a more efficient way of doing this?

Retrieving YouTube subscriber thumbnails over https

Is it possible to show the thumbnails for an embedded YouTube playlist that is subscribing to a feed over https instead of http?
I'm working on an area of a site that is https and retrieving these thumbnails over http is causing a security warning pop-up, which I am trying to get rid of.
The thumbnails are being requested as part of the YouTube API so unable to directly request them over https:
// loop through JSON and assign values to My obj
for (var i = 0; i < len; i ++ ) {
TheVideo.My[i] = {};
ja = jsonArticles[0][i];
TheVideo.My[i].img = ja.media$group.media$thumbnail[0].url;
}
What i'm directly looking for is to call the thumbnail from https instead of http when .url is called in the last line above.
EDIT:
I've found a work around to the problem, but I've edited my original post to clarify a bit what the problem was.
The answer is a bit of an add-on but it does the job. I appended a replace method to request it from https instead of http:
// loop through JSON and assign values to My obj
for (var i = 0; i < len; i ++ ) {
TheVideo.My[i] = {};
ja = jsonArticles[0][i];
TheVideo.My[i].img = ja.media$group.media$thumbnail[0].url.replace('http://','https://');
}
Nice to know that this is possible in these situations.
Hope that this can potentially answer questions for someone else.

Get chrome tabs and windows from localStorage

I am trying to access tabs and windows data inside a Google Chrome extension. I've apparently managed to get this info and loading it through localStorage but I don't know how to use the information, since I can't seem to parse the data back to arrays of objects through JSON parse.
Here's the code:
<html>
<head>
<script>
tabs = {};
tabIds = [];
focusedWindowId = undefined;
currentWindowId = undefined;
localStorage.windowsTabsArray = undefined;
function loadItUp() {
return arrays = chrome.windows.getAll({ populate: true }, function(windowList) {
tabs = {};
tabIds = [];
var groupsarr = new Array();
var tabsarr = new Array();
var groupstabs = new Array();
for (var i = 0; i < windowList.length; i++) {
windowList[i].current = (windowList[i].id == currentWindowId);
windowList[i].focused = (windowList[i].id == focusedWindowId);
groupsarr[windowList[i].id] = "Untitled"+i;
for (var j = 0; j < windowList[i].tabs.length; j++) {
tabsarr[windowList[i].tabs[j].id] = windowList[i].tabs[j];
groupstabs[windowList[i].id] = windowList[i].tabs;
}
}
localStorage.groupsArray = JSON.stringify(groupsarr);
localStorage.tabsArray = JSON.stringify(tabsarr);
localStorage.groupsTabsArray = JSON.stringify(groupstabs);
});
}
function addGroup() {
var name = prompt("NEW_GROUP_NAME");
var groupsarr = JSON.parse(localStorage.groupsArray);
groupsarr.push(name);
localStorage.groupsArray = JSON.stringify(groupsarr);
}
</script>
</head>
<body onload="loadItUp()">
WINDOW_QTY:
<script type="text/javascript">
var wArray = JSON.parse(localStorage.groupsArray);
document.write(wArray);
</script>
<br/>
TABS_QTY:
<script type="text/javascript">
var tArray = JSON.parse(localStorage.tabsArray)
document.write(tArray);
</script>
<br/>
WINDOWS_TABS_QTY:
<script type="text/javascript">
document.write(JSON.parse(localStorage.groupsTabsArray));
</script>
<br/>
</body>
</html>
1)
The page shows bunch of [object Object].
That's expected, objects are implicitly converted to string when you call document.write(tArray);; custom object without a custom toString implementation are converted to "[object Object]". It doesn't mean they're not "parsed".
To inspect the object you can use the Developer Tools. You can open the inspector for a background page from the Extensions page and if you get your page to open in a tab (e.g. if you use chrome_url_overrides) you can inspect it as you would inspect a regular web page.
If you replace the document.write calls with console.log(), you'll be able to inspect the objects in the Developer Tools' console.
2)
Do you realize that the document.write calls in tags run before loadItUp()?
Had no idea that the page code was being executed before loadItUp().
Scripts are executed at the moment they are inserted in the DOM by the parser (unless they are deferred or async) - see MDC documentation on <script>, - while various load events, in particular <body onload=...>, are executed after the page is finished parsing.
So right now your document.write calls print the values that were saved to localStorage the previous time the page was loaded, it's probably not what you wanted.
Instead of using document.write() from inline scripts, you should use element.innerHTML or element.textContent to update the page's text. There are many ways to get a reference to the element you need, document.getElementById() is one.
3)
Last, note that not every object can be saved to and then loaded from localStorage. For example, methods will not survive the round-trip, and the identity of the object is not preserved, meaning that the object you got from a Chrome API will not be the same object after you store it in localStorage and load it back.
You have not explained why you think you need localStorage - it's used when you want to preserve some data after the page is closed and reloaded - so maybe you don't really need it?

Trouble Using LocalStorage to Store Cookie in Mobile Web App

Gurus of SO
I have posted a web app to the iOS Home Screen & want to not have to login each time the app opens up. So I am trying to push the cookie into LocalStorage.
I am using the following code to try to store my cookies in LocalStorage for a mobile web app (code copied from iphone web app ruby gem). But somehow its not working. Any suggestions?
Thank you.
<script type="text/javascript">
(function(){
var RESEND_REQUEST = {{RESEND}};
function isFullScreen(){
return navigator.userAgent.match(/WebKit.*Mobile/) &&
!navigator.userAgent.match(/Safari/);
}
if(isFullScreen()){
if(document.cookie == ''){
var storedValues = localStorage.getItem('__cookie__');
if(storedValues){
var values = storedValues.split(';');
for(var i=0; i < values.length; i++)
document.cookie = values[i];
}
document.cookie = '_cookieset_=1';
if(RESEND_REQUEST){
window.location.reload();
}
}
var lastCookie = null;
setInterval(function(){
if(lastCookie != ''+document.cookie){
lastCookie = ''+document.cookie;
localStorage.setItem('__cookie__', ''+document.cookie);
}
},1000);
}
})()
There are couple thing that does fit in the above code
1. if(document.cookie == '')
The above statement not always suppose return true even when you are opening your web_app from iOS Home Screen for the first time i.e the document.cookie does contain some value (junk though but still) even opening from Home screen(atleast what I found). I urge you to prompt the same with alert
Something like alert(document.cookie) before running into the above mentionif clause
If yes(document.cookie does contain some value) then I guess you need to fix the above if clause something like this
> if(!document.cookie.match(/_session_id/) ) {
> // Rest of the code goes here
> }
if your using ActiveRecord::Base.session_store
or
> if (!document.cookie.match(/{{YOUR SESSION KEY}}/) {
> // Rest of the code goes here
> }
your Session Key if using Cookie Store "the following key can be found my looking at the config/initializer/session_store.rb file
2. As notice the below code
localStorage.setItem('__cookie__', ''+document.cookie)
does make sense when reading though it but there is twist to it
one would except the document.cookie to contain cookie for the application maintained
and stored by the browser but as I notice that document.cookie does not turn out to be same
e.g browser stored the following cookie for my application
"__cookieset=1;KBD=0en-3;_session_id=896c455928f3dd9e7bb0b660efb7063c"
but when inspected the document.cookie I found it to be contain
"__cookieset=1;KBD=0en-3;"
Notice that document.cookie doesnot contain "_session_id=896c455928f3dd9e7bb0b660efb7063c"
Which is must as It used by various authorization gem(devise or authlogic) to determine whether the current user has a valid session ?
so I request you store the cookie from the request object obtain from Rack::Request.new(env)
into the localStorage
3. The middleware placement make sure your placing middleware at right place.
If your using ActiveRecord::Base.session_store I guess the patch code of the same gem can be found here solve your purpose