Opening the result of GET-request with data in a new tab - javascript

I am struggling to find a way in Ajax and JQuery to make a GET-request with data parameters, and to render the response in a new tab in the browser. Something like this:
$('#test-button').on('click', function(e){
var data = {'some_param': [1,2,55,44,3]}
$.get('/test_url/', data, function(html_response) {
// render the HTML contained in html_response in a new tab
});
});

You can do it with:
var newWindow = window.open();
newWindow.document.write(html_response);
But the browser will show a popup alert and you will need to allow it manually.
Working Example:
https://jsfiddle.net/hc3b38bu/

Related

Opening a new tab/window after an AJAX call

I need help making an ajax call and using the response to open a new tab; the code I have sort of works but if the function is called more than once, it will simply replace the contents of the first tab instead of opening another one.
function openInNewTab(url){
let newTab = window.open("about:blank", "new_tab")
$.ajax('api/path').done(function(response){
newTab.location = url + '&data='+response;
})
}
How can I make it so a new tab will be opened each time the function is called?
Try this (url should be full qualified url, e.g. http://www.example.com/path/to/your/file/and/so/on)
function openInNewTab(url){
$.ajax('api/path').done(function(response){
window.open( url + '&data='+response, "_blank");
})
}

get the url of a new page when it is opened after click

I am writing a test that clicks on a button and opens a new tab and directs you to a new website. I want to call in that website value so I may parse it after the rfp code in the webpage name. I then open a decoder site and use it to decode and be sure the decoded webpage name works properly.
The code I'm using:
this.switchesToGetQuotePage = function() {
browser.getAllWindowHandles().then(function(handles) {
newWindowHandle = handles[1]; // this is your new window
browser.switchTo().window(newWindowHandle).then(function() {
getCurrentUrl.then(function(text) {
console.log(text);
});
});
});
};
When I call the getCurrentUrl function it returns below as the value:
data: ,
Use the protractor built in getLocationAbsUrl() to get the url of the current page if its angular based. Here's how -
browser.getLocationAbsUrl().then(function(url){
console.log(url);
});
However if you are working on a non-angular page then do wait until the page loads as the url changes (through redirections) until final page is delivered to the client and then use getCurrentUrl() on the page. Here's how -
var ele = $("ELEMENT_ON_NEW_PAGE"); //replace it with your element on the page
browser.switchTo().window(newWindowHandle).then(function() {
browser.wait(protractor.ExpectedConditions.visibilityOf(ele), 10000).then(function(){
getCurrentUrl.then(function(text) {
console.log(text);
});
});
});
Hope it helps.

Create a link with POST data from chrome extension

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

DOM contains old element after page update

I'm working on a Chrome Extension (no knowledge required for this question...) and when I visit a page with a certain domain, I have a script that is ran. All is does is grab the attribute value from a <meta> tag in the page:
$('meta[itemprop=contentURL]').attr('content')
This works fine on the first page load. However, located within the page there is also links to related content. If I click one of the related links, the Chrome spinner spins a bit, loads the new content, and updates the URL in the address bar.
However, if I try the above jQuery, I get the old attribute value, not the new one on the new page. Upon using Chrome's Inspect Element, I see that the old attribute value is there, but the new one is there if I use view page source instead.
So it seems that the DOM is old...is there a good way to get an updated DOM? This question goes along with all of the other questions of DOM vs Page Source are different threads that I've looked at but didn't get any answers from.
Is there a good way to get a new DOM with the updated attribute? Thanks.
Edit: Here's what the chrome extension code looks like:
chrome.webNavigation.onHistoryStateUpdated.addListener(function(details) {
// request current page , `cache:false`
$.ajax({url:window.location.href, cache:false})
.done(function(data) {
var content = $(data).filter("meta[itemprop=contentURL]").attr("content");
console.log(content);
});
});
The above code logs undefined. Still looking for a good workaround unless the proposed solution is the best one.
Edit, updated
Try
v2 (javascript)
function done() {
var div = document.createElement("div");
var content = this.responseText;
div.innerHTML = content;
content = div.querySelectorAll("meta[itemprop*=contentURL]")[0].content;
console.log(content);
}
var request = new XMLHttpRequest();
request.onload = done;
request.open("GET", window.location.href + "?=" + (new Date().getTime()), false);
request.send();
v1 (javascript utilizing jquery)
// request current page , `cache:false`
$.ajax({url:window.location.href, cache:false})
.done(function(data) {
var content = $(data).filter("meta[itemprop=contentURL]").attr("content");
console.log(content);
});
See jQuery-ajax-settings at cache

Access DOM Content of a specific URL without directly opening the page

How would I go about saving a URL's DOM to a variable without directly opening that page? For example, let's say I have a Chrome extension that allows the user to right click text, search Google, and alert the user with the first result. How would I do this without opening the search results in another tab? Is there any function like saveDOMContent("http://www.google.com/search?q=test") (Note: not a real function) that can do this in pure Javascript?
function getPage(){
var somediv =$('#somediv');
var url='someurl';
var options = {
method:'get',
onSuccess: function(transport){
somediv.innerHTML=transport.responseText;
}
};
new Ajax.Request(url,options);
}
Try something like this, but can not say the same for some cross domain calls

Categories