I have created a chrome extension that sends a POST request to some server and gets its response then displays an number badge according to the data.
Now I want to create a link inside the popup.html based on the data used to send the POST request to the server it self so the users can see the data on the website (data source).
This is the code I use in popup.js to send the POST request
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://someserver/path', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
var regex = new RegExp(/ID:\d+/g);
var testregex = regex.test(this.responseText);
if (testregex == true) {
var count = this.responseText.match(/ID:\d+/g).length;
var countext = count.toString();
chrome.browserAction.setBadgeText({text: countext});
} else {
chrome.browserAction.setBadgeText({text: "0"});
}
};
getCurrentTabUrl(function(url) {
var cleanurl = url.match(/^https?\:\/\/([^\/:?#]+)(?:[\/:?#]|$)/i);
xhr.send('search=' + cleanurl[1] +'&submit=Search');
});
Question is how do I create a link with the same POST data I used before?
Thanks for the help
So, you want to query an external service, then display some information in the popup with a link to more information.
Let's make a scaffold of how you're going to display it. In your popup, include the following:
<div id="data-container">
<div id="data-loading">
<!-- Maybe add an animated spinner here, or something else -->
Loading...
</div>
<div id="data-display">
<!-- Currently empty, will add a link here -->
</div>
</div>
Style this as you wish. Then, from your XHR:
xhr.onload = function () {
/* ... */
// Hide the loading notice
document.getElementById("data-loading").style.display = "none";
// Create the element that will show more details;
// <a href="#"> works okay, but consider making a button
var link = document.createElement("a");
link.href = "#";
link.text = "More details..." // Add data from xhr.responseText?
link.addEventListener("click", clickHandler);
var container = document.getElementById("data-display");
// Make sure the container is empty (in case we're calling this again)
while (container.lastChild) node.removeChild(container.lastChild);
// Append more elements if you want to display some data
container.appendChild(link);
};
Now the interesting part: the clickHandler click handler. To open a new tab from the popup, you should use chrome.tabs.create():
function clickHandler() {
chrome.tabs.create({
url: /* ??? */
});
}
It would be trivial if we wanted to open a normal GET page. To open a POST page, we have to cheat. There are two main possibilities:
Open a javascript: URL that performs a POST. Conceptually easier, but only works for short parameters.
Open a helper page in your extension that will perform POST. This allows you to pass arbitrarily large arguments before the POST happens.
Both are covered in this question: Chrome Extension Development - POST to new tab
Related
I have a Javascript file running on a page and I would like to log certain events as they occur. For example, I have a web store - and when people add an item to their cart, I want to log this event by visiting a page that I built:
function log_event(id) {
window.location.href = 'https://example.com/log/cart.php?id=' + id;
return false;
}
The log/cart.php page doesn't really have anything to display, all it does is insert a record into a database containing the item that was added to the cart, and the date.
The code that calls this function looks like:
document.getElementById('add-to-cart').addEventListener('click', function() {
// Add to the cart
...
// Track the item that was added
let id = document.getElementById('add-to-cart').getAttribute('data-id');
log_event(id);
});
With my current code, the log/cart.php actually replaces the current page. I want the opening of log/cart.php to only happen in the background without the user being interrupted. I don't want it to actually open a browser tab or window and let the user stay in the product page.
You can send an AJAX request to that endpoint:
function log_event(id) {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", 'https://example.com/log/cart.php?id=' + id, true);
xhttp.send();
return false;
}
fetch() can also be used, but be aware of its browser support (no IE).
after get request arrive the values are there and the button disappear
this is the button working on the localhost..
Im trying to add a Facebook share button in a page with dynamic contents like userid, coming from a esp826 server, using java script like innerhtml by ajax call get request once of json when the page body is on-load. When i test in my local host everything is ok since the json file load very fast and before the button loads and so everything works ok. but when i use the esp8266 server the response of the get request come somewhat after the button is loaded and so when it received and the fields get populated with the values the button disappear and remain only a word with a link.
basically the button is working on my localhost... so the innerhtml and everything is ok.. it seems i need to find a way to reload the css or something by the javascript to get the button box alive again.
is there a way to reload the button?
the .json file is just this: getajx.json
{"temp1":"1", "energia":"2", "energiatotal":"3", "tem":"2", "cliente":"22", "usuario":"22"}
you can test on your localhost by placing this getajx.json file having that content in the same directory of the html page is going to work... but i need to know how to make it work if the get request get too long.. please any help???
i tried to add a flag after the response is positive and activate the reloadCss funtion with it but didnt worked
<script>
var temp1, energia, energiatotal, tem, cliente, usuario ;
var ok=0;
function GetAjx() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
ok = 1;
var myObj = JSON.parse(this.responseText);
document.getElementById("temp1").innerHTML = myObj.temp1;
document.getElementById("energiatotal").innerHTML = myObj.energiatotal;
document.getElementById("tem").innerHTML = myObj.tem;
}};
if (ok =1) { function reloadCss(){
var links = document.getElementsByTagName("link");
for (var cl in links){
var link = links[cl];
if (link.rel === "stylesheet")
link.href += "";
}}
};
xmlhttp.open("GET", "getajx.json" , true);
xmlhttp.send();
}
</script>
I found a solution...
apparently i had to change the order of the scripts making the jquery ajax source load first and also tried to put the script from facebook at the bottom of the page...
i took away the reload scripts and other facebook scripts i was testing
and most importantly made the get request false to make it sync instead of async this forces the page to wait for the get request finish..strangely i tried it before and didnt worked this solution perhaps because of the order of the scripts.. can anyone comment on that?
xmlhttp.open("GET", "getajx.json" , false);
was helpful using the f12 on google chrome in specific the performance tab
i decided to not mess up with priority of the scripts even if i tried
any comments i would appreciate
again
thanks for the help
I have a blog set up with homepage that loads the blog entries into the page when the title is clicked (using a javascript function). I would like to be able to send someone a link to a specific entry. In essence is there a way to have a URL that runs enters the the article name into the function. I know this probably doesn't exist so is there a way to achieve this, if not how should I set up my website so that I don't have 50 replications of the 'shell' at each url with the only thing changing is the text inside one element.
Here is a truncated version of the code.
function addArticle (articleName){
var ourRequest = new XMLHttpRequest();
currentArticleId = articleName;
ourRequest.open('GET', 'https://x.neocities.org/' + articleName +'.html');
ourRequest.onload = function(){
var blogPost = ourRequest.responseText;
document.getElementById("on_display").innerHTML = blogPost;
};
ourRequest.send();
}
Note: I have each article stored in its own url which this script grabs.
Thanks for the help!
I am trying to create a temporary image url for a local image and send it to Google to do a Search by Image. I don't want the image url to be permanent so I want to delete it right after I use it. I have the code below:
// Gets a URL that can be used to do a search by image through Google.
function getImageURL() {
var xml = new XMLHttpRequest();
xml.onreadystatechange = function () {
if (xml.readyState == 4 && xml.status == 200) {
deleteImageURL(); // asynchronous call to server to delete the URL
window.location.href =
"https://www.google.com/searchbyimage?site=search&sa=X&image_url="
+ xml.responseText; // the image url
}
}
xml.open("GET", "REST_ENDPOINT", true);
xml.send();
}
The function above calls the server, and when it finishes, will delete the url and redirect the page. The function "deleteImageURL()" is another ajax call done asynchronously. Currently, this loads the google page fine as the image URL is not done deleting the url by the time that the redirect happens.
My question is this: Will deleteImageURL() finish deleting the image URL even after the page redirects or will it stop (and thus, never delete the URL)?
EDIT: So I was thinking about what you guys were saying about race conditions and tried the following code instead:
// Gets a URL that can be used to do a search by image through Google.
function getImageURL() {
var xml = new XMLHttpRequest();
xml.onreadystatechange = function () {
if (xml.readyState == 4 && xml.status == 200) {
deleteImageURL(xml.responseText);
}
}
xml.open("GET", "REST_ENDPOINT"
+ id + "/public_url", true);
xml.send();
}
// Deletes the url for the image.
function deleteImageURL(imageURL) {
var xml = new XMLHttpRequest();
xml.open("GET", "REST_ENDPOINT_FOR_DELETE", true);
xml.send();
window.location.href =
"https://www.google.com/searchbyimage?site=search&sa=X&image_url="
+ imageURL;
}
This code works every time that I run it. I think that there still may be a race condition, but it seems to be working fine so far.
Thanks again.
The "deleteImageURL()" will finish deleting the image URL even after the page redirects..
Refer : Should I wait for ajax to complete to redirect a page?
The server won't stop processing the request (initiated by deleteImageUrl), but you will not be able to handle a callback if the current page unloads in the browser before the operation is completed.
If deleteImageURL(); contains an async call you should do the redirect when the call is completed. Your code will work when the call is synchronious. We don't see the source of deleteImageURL(); and can be more concrete, but you should do the same thing as you've done for getImageURL().
Prerequisites
I have a Website, that displays a page with an input and a button. On the other end is a server that exposes a very basic HTTP API. The API is called like this:
http://127.0.0.1/api/arg1/arg2/arg3
where argX are the arguments. It returns raw HTML. This HTML code needs to be inserted into the Website (another domain). There is a
<div id="container5"></div>
on the website. The HTML needs to be inserted into this container. The code returned by the API is specifically made to be inserted into this container, as it uses CSS classes and scripts from the website, i.e.: the code is not valid for it self.
The Goal
Here is what I have: I've got the API to return what I want, and I got a small JavaScript to run on the website to change the contents of the container:
var element = document.getElementById("container5");
element.innerHTML = "New Contents";
This works so far. Now I need a way to get the HTML from the API to the page. By reading numerous SO questions, it quickly became clear that reading HTML from another URL is close to impossible in JavaScript, due to security constraints.
Is there an easy way to do this with JavaScript or do I need rethink the whole process somehow? One last constraint on my side is that I can only insert JS into the website, I can't - for example - upload a new file to the server.
Edit 1: Workaround!
I solved this for me by using a PHP intermediate file on the requesting server:
<?php
echo file_get_contents('http://example.com');
?>
This will generate a site using the HTML content of any URL. Now the requesting site can read this by using JavaScript:
var getHTML = function ( url, callback ) {
// Feature detection
if ( !window.XMLHttpRequest ) return;
// Create new request
var xhr = new XMLHttpRequest();
// Setup callback
xhr.onload = function() {
if ( callback && typeof( callback ) === 'function' ) {
callback( this.responseXML );
}
}
// Get the HTML
xhr.open( 'GET', url );
xhr.responseType = 'document';
xhr.send();
};
This modifies any element:
var element = document.getElementById("resultpage");
getHTML( 'http://localserver.org/test.php', function (response) {
element.innerHTML = response.documentElement.innerHTML;
});
Checkout CORS https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
also JSONP in same article.