Modify HTTP Request value in Chrome automatically - google-chrome

Is there a way or an app to always change the value of a POST Request to a specific URL in Chrome?

Try chrome.webRequest. Specifically, chrome.webRequest.onBeforeRequest.addListener
You would provide the string ["blocking"] as an attribute for the opt_extraInfoSpec parameter, and as a return value provide an object of type BlockingResponse which specifies what changes you want to make to the request.
Also, to get the body of the POST request, opt_extraInfoSpec also needs to contain the string "requestBody"
Your code would look something like this:
chrome.webRequest.onBeforeRequest.addListener( function(details){
//
if(details.method == "POST")
var new_url = "http://stackoverflow.com/my_new_url";
return {redirectUrl: new_url};
}, ({urls: ["http://*/*", "https://*/*"] }), ["blocking", "requestBody"]);
Dcoumentation at https://developer.chrome.com/extensions/webRequest
EDIT: The code you would place in the background page only.

Related

NativeScript Throwing Error Response with status: 200 for URL: null

I am using Angular4 with TypeScript version 2.2.2
My web app is running fine when I call JSON with Filters but my NativeScript app fails when I call the Filter Values as an Object but works fine when I call filter values as a string.
Error Response with status: 200 for URL: null
THIS WORKS
https://domainname.com/api/v1/searchevents?token=057001a78b8a7e5f38aaf8a682c05c414de4eb20&filter=text&search=upcoming
If the filter value and search value is STRING it works whereas if they are objects as below, it does not work
THIS DOES NOT WORK
https://api.domainname.com/api/v1/searchevents?token=057001a78b8a7e5f38aaf8a682c05c414de4eb20&filter={"limit":"12","skip":"0"}&search={"search":"","latitude":"","longitude":"","categories":"","address":"","type":"upcoming"}
The Code I used is below
getData(serverUrl, type, skip_limit) {
console.log(serverUrl);
let headers = this.createRequestHeader();
let token_value = localStorage.getItem('access_token')
let url;
var filter;
filter = '{"limit":"10","skip":"0"}'
url = this.apiUrl + serverUrl + '?token=' + token_value + '&filter=' + filter
return this.http.get(url, { headers: headers })
.map(res => res.json());
}
The URL as formed above for the API is fine and works fine. Yet the error comes Error Response with status: 200 for URL: null
CAN ANYONE HELP ME SOLVE THIS?
Looks like the issue is the "filter" values are of different type and from what you mentioned as what worked, your service is expecting a string and not an object/array. So it fails to send the proper response when it gets one. With an object in the URL, you may have to rewrite the service to read it as an object (parse the two attributes and get them individually)
To make it simple, you can make these two as two different variables in the URL. like below,
https://api.domainName.in/api/v1/oauth/token?limit=10&skip=0
Be more precise in whats happening in your question,
1) Log the exact URL and post it in the question. No one can guess what goes in "text" in your first URL.
2) Your URL which you mentioned as worked have "token" as part of path, but in the code, its a variable which will have a dynamic value from "token_value".
3) Post your service code. Especially the signature and input parsing part.
Got the solution:
All you have to do is encode the Filter and Search Parameters if it is an Object or Array using Typescript encodeURI()
var filter = '{"limit":"12","skip":"0"}'
var search = '{"search":"","latitude":"","longitude":"","categories":"","address":"","type":"upcoming"}'
var encoded_filter = encodeURI(filter);
var encoded_search = encodeURI(search);
url = this.apiUrl+serverUrl+'?token='+token_value+'&filter='+encoded_filter+'&search='+encoded_search

Dynamically create and submit a form

I have some data in my model which I want to put into a request body and send it with a POST request. The problem is I want the browser to navigate to the request URL because the route returns a new HTML page. Normally this would be done by putting the data in a form and then using JS to submit it.
How can I do this with Elm?
Edit - Updated based on your comment clarification
As I understand your question, you want to be able to construct a POST request behind the scenes but let the browser post it so that the browser is redirected to the actual page it is posted, leaving your Elm app behind.
You could build up the form in Elm but keep it hidden, then when you want to trigger it, pass the form ID to a port which performs the form submission.
type alias Model =
{ foo : String }
view model =
div []
[ Html.form
[ id "my-form"
, action "https://requestb.in/1crya751"
, method "POST"
, style [ ( "display", "none" ) ]
]
[ input [ type_ "text", name "foo", value model.foo ] []
]
, div []
[ button [ onClick SubmitForm ] [ text "Submit" ] ]
]
type Msg
= SubmitForm
update msg model =
case msg of
SubmitForm ->
model ! [ submitForm "my-form" ]
port submitForm : String -> Cmd msg
Your javascript could look something like this (albeit with some error handling in case the id doesn't exist):
var app = Elm.Main.fullscreen()
app.ports.submitForm.subscribe(function(formId) {
document.getElementById(formId).submit();
});
Here is a working example of this on ellie-app.com. It posts the form to requestb.in so you can see what has been posted by going here.
The reason I'm recommending a hidden form instead of trying to use the standard Http packages is because it sounds like you want the browser to be redirected to whatever form you are posting to. You couldn't really achieve the same thing by using the Http packages.

Chrome API responseHeaders

Based on this documentation: https://developer.chrome.com/extensions/webRequest.html#event-onHeadersReceived
I tried to display the response via the console like:
console.log(info.responseHeaders);
But its returning undefined.
But this works though:
console.log("Type: " + info.type);
Please help, I really need to get the responseHeaders data.
You have to request the response headers like this:
chrome.webRequest.onHeadersReceived.addListener(function(details){
console.log(details.responseHeaders);
},
{urls: ["http://*/*"]},["responseHeaders"]);
An example of use. This is one instance of how I use the webRequest api in my extension. (Only showing partial incomplete code)
I need to indirectly access some server data and I do that by making use of a 302 redirect page. I send a Head request to the desired url like this:
$.ajax({
url: url,
type: "HEAD"
success: function(data,status,jqXHR){
//If this was not a HEAD request, `data` would contain the response
//But in my case all I need are the headers so `data` is empty
comparePosts(jqXHR.getResponseHeader('redirUrl')); //where I handle the data
}
});
And then I silently kill the redirect while scraping the location header for my own uses using the webRequest api:
chrome.webRequest.onHeadersReceived.addListener(function(details){
if(details.method == "HEAD"){
var redirUrl;
details.responseHeaders.forEach(function(v,i,a){
if(v.name == "Location"){
redirUrl = v.value;
details.responseHeaders.splice(i,1);
}
});
details.responseHeaders.push({name:"redirUrl",value:redirUrl});
return {responseHeaders:details.responseHeaders}; //I kill the redirect
}
},
{urls: ["http://*/*"]},["responseHeaders","blocking"]);
I actually handle the data inside the onHeadersReceived listener, but this way shows where the response data would be.

How do I get rid of recursive AJAX requests for a childless node?

Problem:
According to the author, jsTree Documentation:
When opening a closed node (that has no loaded children) an AJAX request is made.
How do I configure jsTree to get rid of these AJAX data requests made for each empty/childless node? I want my empty nodes remain empty (or childless)!
Given (simplified):
JSON data container (data.json)
{
"data" : "Root node with no children",
"children" : []
}
jsTree configuration
{
"json_data" : {
"ajax" : {
"url" : "data.json",
"type" : "GET",
"dataType" : "json",
"dataFilter" : function (data, type) {
//some filtering function
}
}
},
"plugin" : ["json_data"]
}
Mark the state of the leaf node as "leaf". That should fix it.
I have had this problem setting the attribute state="closed" on childless nodes for XML trees. Removing the state attribute solves the issue.
I had a similar problem a couple of weeks ago. I had a function call in the "url" field, which ultimately led to java code that made a JSON string based on a SQL query. So when I clicked on a childless closed node, the function was called again, resulting in an endless tree.
the way I solved this was:
"json_data" : {
"ajax" : {
"url" : "getAreaTree?treeType=Areas&ownerPhone=<%=webSessionObject.getUserPhoneNum()%>",
"data" : function (n) {
return { id : n.attr ? n.attr("id") : 0 };
}
}
},
The result of the function defined in "data" will be added as a parameter to the "url" function. Then I can check whether the parameter was 0 (initial load) or 1 (the id of my root) or something else.
If this doesn't work for you, maybe you could try something like this:
.bind("before.jstree",function(event,data){
if(data.func === "create"){
var foo = true;
data.inst._get_node(null, true).each(function () {
if(this.id!=rootId && this.id!=0){
foo = false;
})
if(!foo){
event.stopImmediatePropagation();
return false;
}
}
})
I'm not exactly sure this works though. "before.jstree" fires before all events. I'm checking whether the function about to fire is "create", and if it is I check the id of the selected node. If it's something else than my root's id or 0 (initial load) I stop the create function.
I use a similar structure for a different situation, so something like this should work. It could be that the "create" event is not what you should be binding to though. You can change it to
.bind("before.jstree",function(event,data){
console.log(data.func)
if(data.func === "create"){
To see which functions are called.
Just skip the children attribute. Obviously your node has no children, but you specify the attribute? Simply skip it, the node will be rendered as a leaf node and no further requests will be made.
I've been struggling with this problem too. I got the main idea from jsTree - loading subnodes via ajax on demand
The basic problem is that when we click a child node that is not set to leaf, a new AJAX request is generated with the URL we set in the tree configuration. The trick seen in the above link is to provide a function instead of a static URL string. My jstree is used to display a directory structure on the server, so I can arrange to dynamically add to the URL for sub-directories. If you assign a function to the url property of the ajax property in your jstree configuration, the function receives the node you clicked as an argument. My nodes display the names of directories or files so I can use the text() function to get the raw directory name. There seems to be some space in front of the name returned in this way, so I used a String trim() function and then encodeURIComponent to give me something I can use in a URL.
If -1 is passed to the url function, then you're at the root and you can safely use your base URL. Now, this only works for the first level of the hierarchy. I've got a bit more work to do, adding the full path to the metadata of the node or something like that, but this idea might put you on the right track. It looks as if it's not exactly a bug but by design. You have to make sure a request triggered by a subnode sends a suitable URL to the server.
Here's the url property I've assigned to the ajax object in my jstree configuration:
"url": function (node) {
var subDirectory = "",
url = "";
if (node === -1)
{
url = "/tree_service/tree/format/json?path=exercises";
}
else
{
subDirectory = encodeURIComponent(node.text().trim());
url = "/tree_service/tree/format/json?path=exercises/" + subDirectory;
}
return url;
}
My plan is to build the URL cumulatively by polling the node for its full path, then adding the node's name as above to create the final URL. Pseudo code:
//haven't figured out how to add the path to the node and then retrieve it
path = node.metadata.path;
path = encodeURIComponent(path);
subDirectory = encodeURIComponent(node.text().trim());
url = path + "/" + subDirectory;
UPDATE
See my answer here how to get the metadata of jsTree. about getting the metadata from the node using node.data().path

Using Json in KRL

I'm having trouble with parsing my Json, when i place the url in the browser i get this as a return {"token": "7xv6r32eay5n376", "secret": "589bc72ix7mowua"} So all i want to do is get that string and parse out the token and secret and display the values in a notify to confirm i'm getting the correct information. Can anyone see what i'm doing wrong?
rule first_rule {
select when pageview ".*" setting ()
pre{
json=http:get(/* I place my URL here */);
content = json.pick("$..content");
token=content.decode();
tok=token.pick("$..token");
sec=token.pick("$..secret");
message="Token: "+tok+" "+"Secret: "+sec;
}
notify("Values: ",message);
}
}
so i fixed my KRL problem, I guess when using http:get(); you must use double quotes "" not single '' in the get().