I have a contextMenu item which sends an Ajax request to a PHP script on my website.
The PHP script creates a .txt file and returns the download URL to the extension again.
On the next step a Desktop Notification is shown and there I want to place the download link, so the user can download the created file.
The problem is that I can't use HTML there. I don't want to use createHTMLNotification which is deprecated, so my code is:
var url = 'http://mydomain.com/somefile.txt';
var notification = window.webkitNotifications.createNotification(
'48.png', 'Click to download', 'Some description');
notification.addEventListener('click', function() { // can't create <a> tag, so I'm tring with a click event.
notification.cancel();
window.open(url);
});
notification.show();
This (window.open()) opens the file in a new tab. But I want only to download it, without opening in the browser.
Any ideas?
I found a solution and since there are not any answers I will write it.
For downloading a file from given URL you can use the downloads API's download method:
function forceDownload(url) {
var filename = url.replace(/^.*\/|\.[^.]*$/g, ''); // get basename
chrome.downloads.download(
{url: url, saveAs: true}, // options array
function(id) {
// callback function
}
);
};
In my situation forceDownload() method is called in the Ajax' done method:
function exportEntries(info, tab) {
var user = 'blah blah';
$.ajax({
url: 'http://domain.com/export.php',
method: 'POST',
data: { topic: tab.url, user: user }
}).done(function ( url ) {
forceDownload(url);
});
}
Related
I have a link on my site. When clicked it'll call a function that does a mongoose query.
I'd like the results of that query to be sent to the same page in a variable without reloading the page. How do I do that? Right now it is just rendering the page again with new query result data.
// List comments for specified chapter id.
commentController.list = function (req, res) {
var chapterId = req.params.chapterId;
var query = { chapterId: chapterId };
Chapter.find({ _id: chapterId }).then(function (chapter) {
var chapter = chapter;
Comment.find(query).then(function (data) {
console.log(chapter);
Chapter.find().then(function(chapters){
return res.render({'chapterlinks', commentList: data, user: req.user, chapterq: chapter, chapters:chapters });
})
});
})
};
You just need to make that request from your browser via AJAX:
https://www.w3schools.com/xml/ajax_intro.asp
This would be in the code for your client (browser), not the code for your server (nodejs).
UPDATE:
Here's a simple example, which uses jQuery to make things easier:
(1) create a function that performs and handles the ajax request
function getChapterLinks(chapterId) {
$.ajax({
url: "/chapterLinks/"+chapterId,
}).done(function(data) {
//here you should do something with data
console.log(data);
});
}
(2) bind that function to a DOM element's click event
$( "a#chapterLinks1" ).click(function() {
getChapterLinks(1);
});
(3) make sure that DOM element is somewhere in you html
<a id="chapterLinks1">Get ChapterLinks 1</a>
Now when this a#chapterLinks1 element is clicked, it will use AJAX to fetch the response of /chaptersLink/1 from your server without reloading the page.
references:
http://api.jquery.com/jquery.ajax/
http://api.jquery.com/jquery.click/
Basically my code contains two modules. One to update the data in an ajax call and another module loads the response from an external php to a element. I am trying to implement a chat mechanism. Where user texts data and gets updated chat history without loading the page
The submit ajaxsubmit.php wont work properly with the load fetch-conversation.php loading chat data. This results in execution of alert("Please Fill All Fields")
function auto_refresh()
{
if(writing==false){$('#message-container').load(<?php echo "'fetch-conversation.php?id=$id'"?>);}
}
setInterval('auto_refresh()', 1000);
<script>
var writing=false;
$(document).ready(function(){
$("#submit").click(function(){
writing=true;
var content = $("#content").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'content='+ content ;
if(content=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
writing=false;
}
});
}
return false;
});
});
</script>
I have a script to test that - on click - generates an iFrame which downloads a file. How can I intercept the response with CasperJS?
I already tried the sequence:
casper.click('element');
casper.withFrame('frame', function(){
console.log(this.getCurrentUrl()); // only return about:blank, but should have URL
console.log("content: " + this.getHTML()); // Yep, empty HMTL
this.on('resource.received', function(resource){
console.log(resource.url); // never executed
});
});
I need the content of the file but can not really produce the URL without clicking the element or changing the script I'm testing.
Ideas?
I tried other events, but none got fired when downloading via the iframe. I found another solution that works - but if you have something better, I'd like to try it.
Here it comes:
// Check downloaded File
.then(function(){
// Fetch URL via internals
var url = this.evaluate(function(){
return $('__saveReportFrame').src; // JavaScript function in the page
});
var file = fs.absolute('plaintext.txt');
this.download(url, file);
var fileString = fs.read(file);
// Whatever test you want to make
test.assert(fileString.match(/STRING/g) !== null, 'Downloaded File is good');
})
I use Aspose to generate a Word document. It must be opened in the browser automatically when it comes back from the server.
Here is my code:
Do Ajax call to get the document
$.ajax({
url: "Export/StreamWord",
data: { topicId: CurrentTopic.id },
success: function (result) {
//Nothing here. I think that the browser must open the file automatically.
}
});
Controller .NET MVC 3
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult StreamWord(string topicId)
{
var stream = new MemoryStream();
Document doc = exportRepos.GenerateWord(topicId); //Document is a Aspose object
doc.Save(stream, SaveFormat.Docx);
stream.WriteTo(Response.OutputStream);
return File(stream, "application/doc", "test.doc");
}
BUT when I run it from the browser nothing happen.
Response from the server you can see on the image. Document comes, but it is not been opened.
Any suggestions?
Do not use AJAX for this, just use a simple page redirect instead. If you use a page redirect it will prompt the user to download the file, it won't actually move them away from the current page.
The code would look like
document.location.href = "Export/StreamWord?topicId=" + CurrentTopic.Id;
What you're attempting is not possible with AJAX.
I am calling the Facebook Add Page Tab Dialog using the Javascript SDK as follows:
var obj = {
method: 'pagetab'
};
FB.ui(obj, function(response) {
console.log(response);
});
The dialog shows up on the page and then auto redirects to the same page which is presently open. It doesn't show the options to select the pages as described in the docs.
Got it working now. The 'display' parameter should be specified explicitly to 'popup'
var obj = {
method: 'pagetab',
display: 'popup'
};
FB.ui(obj, function(response) {
console.log(response);
});