bookmarklet to add a parameter to the url and resubmit it? - javascript

Is the following possible with a bookmarklet?
Add an additional parameter to the URL (include_docs=true)
Re-submit the URL
I have this but it fails silently on firefox. I haven't tried it with another browser:
javascript:(
function()
{
key = encodeURI('include_docs'); value = encodeURI('true');
var kvp = document.location.search.substr(1).split('&');
var i=kvp.length; var x; while(i--)
{
x = kvp[i].split('=');
if (x[0]==key)
{
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if(i<0) {kvp[kvp.length] = [key,value].join('=');}
//this will reload the page, it's likely better to store this until finished
document.location.search = kvp.join('&');
}()
);

No need to over-complicate anything ;-)
document.location += '&include_docs=true';
That should do the trick. In bookmarklet form:
javascript:(function(){document.location+='&include_docs=true'}());

Related

Make every link or page with a dedicated reading page

I am trying to make every link or page with a dedicated reading page. For example, I have a lot of pages when visiting one page, storage is made, but the problem comes when he visits another page. He does not start again. He goes to the last id. I want to make each page with its own address.
<script>
window.onunload = function() {
var url_string = window.location.href ;
var url = new URL(url_string);
var value = document.getElementById("pageNumber").value;
localStorage.setItem("last", value , url_string );
var c = url.searchParams.get("c");
};
window.onload = function(){
var url_string = window.location.href ;
var url = new URL(url_string);
var c = url.searchParams.get("c");
var value = localStorage.getItem("last" , url_string);
if(value) {
document.getElementById("pageNumber").value = value;
window.location.href = "#" + value;
}
};
How do I do that and make each link have private storage
Another example https://hululkitaab.com/test/cct.html
https://hululkitaab.com/test/fcvcb.html
If you visited the first link and went to page number 20
When you visit the following link, it will return you to number 20 I do not want this any suggestions
what about this:
const pageName = "myPageName";
localStorage.setItem(pageName + "last", value);

Send multiple parameter in ajax request using javascript

So I want to use ajax request and I know how to use it.
But problem that i had that I want to pass parameters to request. So My first page had 4 parameter then I build url like this,
var url = "./ControllerServlet?PAGE_ID=BPCLA&ACTION=closeAssessment&SAVE_FLAG=true&closeReason="+closeReasonStr+"&closeCmt="+closeCmt;
but now parameter is increasing like now I have 20 more. So now building url like this going to be messy approach. Is there a better way to do this.
Here is my function where i am building URL in javascript function.
function closeAssessment() {
var closeReason = document.getElementById("SectionClousureReason");
var closeReasonStr = closeReason.options[closeReason.selectedIndex].value;
var closeCmt=document.getElementById("SectionCloseAssessmentCmt").value;
var url = "./ControllerServlet?PAGE_ID=BPCLA&ACTION=closeAssessment&SAVE_FLAG=true&closeReason="+closeReasonStr+"&closeCmt="+closeCmt;
ajaxRequest(url);
return;
}
edit:
As you ask here is my ajaxRequest function,
function ajaxRequest(url) {
strURL = url;
var xmlHttpRequest = false;
var self = this;
// Mozilla, Safari
if (window.XMLHttpRequest) {
self.xmlHttpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
self.xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpRequest.open("POST", strURL, true);
self.xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
self.xmlHttpRequest.onreadystatechange = function() {
if (self.xmlHttpRequest.readyState == 4) {
if (self.xmlHttpRequest.status == 200) {
var htmlString = self.xmlHttpRequest.responseText;
var parser = new DOMParser();
var responseDoc = parser.parseFromString(htmlString, "text/html");
window.close();
} else {
ajaxFailedCount++;
// Try for 1 min (temp fix for racing condition)
if (ajaxFailedCount < 1200) {window.setTimeout(function() {ajaxRequest(url)}, 50);}
else {alert("Refresh failed!")};
}
}
}
self.xmlHttpRequest.send(null);
}
You could make an object with the key/value pairs being what you want added to the URL.
var closeReason = document.getElementById("SectionClousureReason");
var params = {
PAGE_ID: 'BPCLA',
ACTION: 'closeAssessment',
SAVE_FLAG: 'true',
closeReasonStr: closeReason.options[closeReason.selectedIndex].value,
closeCmt: document.getElementById("SectionCloseAssessmentCmt").value
};
Then add them to the URL via a loop.
var url = "./ControllerServlet?";
var urlParams = Object.keys(params).map(function(key){
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
url += urlParams;
ajaxRequest(url);
Note: I added encodeURIComponent just to be safe.
EDIT: From your comment, it seems you want to submit a <form> but you want to use AJAX to do so. In that case, you can loop over the form elements and build the above params object.
var params = {
PAGE_ID: 'BPCLA',
ACTION: 'closeAssessment',
SAVE_FLAG: 'true'
};
var form = document.getElementById('yourForm'),
elem = form.elements;
for(var i = 0, len = elem.length; i < len; i++){
var x = elem[i];
params[x.name] = x.value;
}
Build up an object of your parameters and put them in the uri through a loop like this:
var values= {
page_id: 'BPCLA',
action: 'test'
},
uri_params = [],
uri = 'http://yoururl.com/file.php?';
for (var param in values) uri_params.push( encodeURIComponent( param ) + '=' + encodeURIComponent( values[ param ] ) );
uri = uri + uri_params.join( '&' );
console.log( uri );
Or consider using POST to transport your parameters, as many browsers have limitations on the query string.
Edit: you can also build yourself a function which traverses your form and builds up the values object for you so you don't have to do it manually.
Be aware however that anyone can inject custom url paramters simpy by appending form elements before submitting the form (by using the developer tools for example) so keep that in mind.
If you are using jQuery you can use .serializeArray() or have a look at this answer for a possible function you could use.

Get pathname along with PHP vars using JavaScript?

I want to save an entire URL paths to a variable, including the php vars, eg:
mysite.com/pagename?id=2
I can use
var pathname = window.location.pathname;
but this only retrieves the URL without the variables.
Is there a function to retrieve the URL as a literal string?
This should work
window.location.href
Have you tried see if it works:
document.URL
Can you try this,
// Get current page url using JavaScript
var currentPageUrl = "";
if (typeof this.href === "undefined") {
currentPageUrl = document.location.toString().toLowerCase();
}
else {
currentPageUrl = this.href.toString().toLowerCase();
}
Ref: http://www.codeproject.com/Tips/498368/Get-current-page-URL-using-JavaScript
It's hard , this answer explains how to implement it from the top response:
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {}, tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
//var query = getQueryParams(document.location.search);
//alert(query.foo);

How do you get the current sessid from web address and use it in javascript?

Sorry if this is a noob question, network admin unknowingly turned into web developer :) I am trying to understand how to get the current sessid and put it into the javascript where sessid= (current sessid), its on the web address and is generated when you visit the search page. ex: http://www.southerntiredirect.com/shop/catalog/search?sessid=uUQgRHQyekRGJcyWwTFwf5hxep7cdYlV4CdKfunmjxNOQPEgDZdJD2tNgRsD7Prm&shop_param=
<script language="JavaScript">
var url= "http://www.southerntiredirect.com/online/system/ajax_search_manufacturer?sessid=????????";
</script><script type="text/javascript" src="http://www.southerntiredirect.com/online/templatemedia/all_lang/manufacturer.js"></script><input type="hidden" name="sessid" value="sessid??????">
Use my handy-dandy library URLTools!
Library
//URLTools- a tiny js library for accessing parts of the url
function urlAnalyze(url) {
if (url == undefined) {var url = document.location.toString();}
url = url.replace(/\%20/g," ");
//seperates the parts of the url
var parts = url.split("?");
//splits into sperate key=values
if (parts[1] == undefined) {return 1;}
var keyValues = parts[1].split("&");
var key = function () {}
keyValues.forEach(function (keyValue) {
var keyAndValue = keyValue.split("=");
key[keyAndValue[0]] = keyAndValue[1];
});
return key;
}
Then, just call URLAnalyze and get the sessid key.
Usage
var urlKeys = urlAnalyze(),
sessid = urlKeys["sessid"];
here is a great function that grabs whatever you want and returns the key, value for it.
The main portion of this function gets the url using window.location.href and then performs a regular expression on it to find botht he key and the value.
I DO NOT TAKE CREDIT FOR THIS CODE.
Please go the link to see the full example
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(
/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
You could use a simple regexp:
var url = "http://www.southerntiredirect.com/shop/catalog/search?sessid=uUQgRHQyekRGJcyWwTFwf5hxep7cdYlV4CdKfunmjxNOQPEgDZdJD2tNgRsD7Prm&shop_param=";
var match = url.match(/sessid=([^&]+)/);
if (match === null) {
throw new Error("now what? D:");
}
var sessid = match[1];
The regexp in English: look for "sessid=" then capture anything that isn't an &

How do I change the flashvars using the ContentScript of a Chrome Extension?

I want to create a chrome extension to help me debug my swf, and I'd like the extension to be able to change some of the flashvars while keeping others untouched.
I can't imagine this is a new or unique problem, so before I reinvent the wheel, I'm asking if anyone here has examples of it being done, or how to do it.
I've tried searching, but my googlefu seems to be off.
My use case is as follows. I have a Google Chrome extension which has a few drop down menus with possible flash var values. I want the change the values in the drop down, and then reload the swf with these new flashvars, but without changing flashvars which are not in my drop down menus.
I'm able to easily inject a new swf on the page with the values from my dropdown menus, however I'd like to be able to reload, rather than recreate, the swf.
I have tried using Jquery to pull all the flash vars like this:
var flashVars = $("param[name=flashvars]", gameSwfContainer).val();
However, I'm having a hard time changing or replacing just a couple of the values, and then injecting them back into the object. (Regex might be helpful here unless there is a better way?)
Thanks for your help.
Currently, I am trying to do the following, but I'm not sure if it's the right direction.
ContentScript.js
//Setup
var swfVersionStr = "10.1.0";
var xiSwfUrlStr = "playerProductInstall.swf";
var params = {};
params.quality = "high";
params.bgcolor = "#000000";
params.allowscriptaccess = "always";
params.allowfullscreen = "true";
var attributes = {};
attributes.id = "game_swf_con";
attributes.name = "game_swf_con";
attributes.class = "game_swf_con";
attributes.align = "middle";
var InjectedFlashvars = {
"run_locally": "true",
//.. some other flash vars that I won't be changing with my extension
"swf_object_name":"game_swf"
};
// Injection code called when correct page and div detected;
var injectScriptText = function(text)
{
loopThroughLocalStorage();
swfobject.embedSWF(
swfName, "game_swf_con",
"760", "625",
swfVersionStr, xiSwfUrlStr,
InjectedFlashvars, params, attributes);
swfobject.createCSS("#game_swf_con", "display:block;text-align:left;");
};
function loopThroughLocalStorage()
{
for(key in localStorage){
try{
var optionArray = JSON.parse(localStorage[key]);
var option = returnSelectedFlashVar(optionArray);
var value = option.value ? option.value : "";
InjectedFlashvars[key] = value;
} catch(err){}
}
}
function returnSelectedFlashVar(optionArray){
for(var i= 0; i < optionArray.length;i++)
{
if(optionArray[i].selected == true)
{
return optionArray[i];
}
}
}
Overall, I currently have contentscript.js, background.js, options.js, options.html, popup.html and popup.js The code above so far only exists in contentscript.js
Had a little trouble deciding what you actually wanted.
But if its manipulating the values in the flashvar maybe this will help...
queryToObject = function(queryString) {
var jsonObj = {};
var e, a = /\+/g,
r = /([^&=]+)=?([^&]*)/g,
d = function(s) {
return decodeURIComponent(s.replace(a, " "));
};
while(e = r.exec(queryString)) {
jsonObj[d(e[1])] = d(e[2]);
}
return jsonObj;
}
objectToQuery = function(object) {
var keys = Object.keys(object),
key;
var value, query = '';
for(var i = 0; i < keys.length; i++) {
key = keys[i];
value = object[key];
query += (query.length > 0 ? '&' : '') + key + '=' + encodeURIComponent(value);
}
return query;
}
// this is what a flashvar value looks like according to this page...http://www.mediacollege.com/adobe/flash/actionscript/flashvars.html
var testQuery = 'myvar1=value1&myvar2=value2&myvar3=a+space';
var testObject = queryToObject(testQuery);
console.debug(testObject);
testQuery = objectToQuery(testObject);
console.debug(testQuery);
testObject.myvar0 = 'bleh';
delete testObject.myvar2;
console.debug(objectToQuery(testObject));
And if your using localStorage in a content script then be aware that the storage will be held in the context of the page.
Try looking at chrome.storage instead.
EDIT : Answer to comments
This looks correct, but how do I "reload" the object so that those new flashvars are the ones that are used by the swf?
Ive never used swfObject (havent done any flash stuff in like 5 years) but had a look and it looks like you can just rerun the swfobject.embedSWF with the new flashVars and it will replace the old object with the new one. Which is fine if your replacing one that you added yourself as you can supply all of the details, if your replacing something put there by someone else you could clone the object, change some stuff and replace the original with the clone. Cloning will not clone any events attached to the element but I dont think thats a problem in your case. Here's an example (which I couldnt test as I couldnt find any simple sample swf that just prints the flashvars)....
var target = document.querySelector('#game_swf_con');
// Cloning the element will not clone any event listners attached to this element, but I dont think that's a prob for you
var clone = target.cloneNode(true);
var flashvarsAttribute = clone.querySelector('param[name=FlashVars]');
if (flashvarsAttribute) {
var flashvars = flashvarsAttribute.value;
flashvars = queryToObject(flashvars);
// add a new value
flashvars.newValue = "something";
// update the clone with the new FlashVars
flashvarsAttribute.value = objectToQuery(flashvars);
// replace the original object with the clone
target.parentNode.replaceChild(clone, target);
}​
Sources:
a) Content Scripts
b) Background Pages
c) Message Passing
d) tabs
e) Browser Action
f) API()'s
Assuming a html page containing following code
<embed src="uploadify.swf" quality="high" bgcolor="#ffffff" width="550"
height="400" name="myFlashMovie" FlashVars="myVariable=Hello%20World&mySecondVariable=Goodbye"
align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash"
pluginspage="http://www.adobe.com/go/getflash" />
I try to get following get height of embed object and change it.
Sample Demonstration
manifest.json
{
"name":"Flash Vars",
"description":"This demonstrates Flash Vars",
"manifest_version":2,
"version":"1",
"permissions":["<all_urls>"],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["myscript.js"]
}
]
}
myscript.js
// Fetches Current Width
width = document.querySelector("embed[flashvars]:not([flashvars=''])").width;
console.log("Width is " + width);
// Passing width to background.js
chrome.extension.sendMessage(width);
//Performing some trivial calcualtions
width = width + 10;
//Modifying parameters
document.querySelector("embed[flashvars]:not([flashvars=''])").width = width;
background.js
//Event Handler for catching messages from content script(s)
chrome.extension.onMessage.addListener(
function (message, sender, sendResponse) {
console.log("Width recieved is " + message);
});
Let me know if you need more information.

Categories

Resources