I want to load bing images pages "http://www.bing.com/images/search?q=home+design&qft=+filterui:imagesize-large&safe=off" , and save this url as html with javascript.
here is my code sample that I try :
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
link.click();
}
but this code is send file to download on browser.
whether this may be done save url on server with javascript?
Suggestion and corrections are welcome.
One way to do this is with iframes, although it might not always be available for every site. But Bing seems to be ok with using iframes. I just tried adding the specific URL you listed into an iframe with the following HTML code and it worked:
<iframe src="http://www.bing.com/images/search?q=home+design&qft=+filterui:imagesize-large&safe=off"></iframe>
For other sites, such as Google, it might not be so easy. Google doesn't allow anything to be loaded in iframes by default, however it seems they will allow specific searches to be configured in your google account and display in iframes on sites you specify.
To achieve with Javascript (since the question mentions javascript) you can just leave the "src" attribute blank and set it using the script, for example if you only have one iframe on the page
document.getElementsByTagName('iframe')[0].src="http://www.bing.com/";
Related
Please guide me. Is possible to read script tag src URL content using JavaScript/jQuery. Please don't suggest JSON/Ajax/iframe options.
I have tried like
<script src="http://www.test.com" id="test">
document.getElementById('test').src
but it give only src URL.
My Exact requirements is,
I have two application, each in different web server with www.siteA.com and www.siteB.com.
In Server2, I have cross origin and iframe restriction to access the application. Example: If a request is coming from server1(siteA) to server2(siteB) via Ajax or iframe, it's restricted to access the siteB page content. But If I load siteB in script tag it's loaded, but I'm not able to get the content.
So I mentioned above, don't suggest iframe and Ajax. Help me to achieve this.
The best way really is AJAX, but it does sound like CORS is an issue for you. The only other option I can think of would be to open the page in a new browser window, although I don't know what kind of user experience implications that will have on your application.
You can open a new browser window by:
function showContent(){
var url = document.getElementById("test").src;
window.open(url, "_blank");
}
Although if you take this route, you shouldn't put the url on a script tag, because the browser will download it once (via the script tag), and then a second time on the window.open.
In my app I have a UIWebView which shows content generated from WP (HTML code generated from Facebook embedding).
The content HTML is loaded with loadHMTLString:baseURL: method (where for base URL I use URL to mainBundle file path, because of a local CSS file). The videos I've tried and have problems with are set to Public visibility.
The problem I am facing is that when the content contains a Facebook embedded video, the video is not shown. Instead, in the place where it should be placed, there is a blank space.
I've had a similar problem showing an embedded post from Twitter, or Instangram (not the same kind of problem tho. Here, there was a post frame, but it was without a picture, or text). I have solved it by adding "http:" to the javascript file link. That solution doesn't work for facebook video problem.
Also, I've tried using WKWebView, without any luck. I have tried searching for a similar problem here, but I haven't found one.
Any help is appreciated.
where for base URL I use URL to mainBundle file path
HTML documents which include the Facebook Javascript SDK do not execute that SDK properly within a UIWebView, unless the baseURL parameter is set to an external website.
That is,
someUIWebView.loadHTMLString(HTMLString, baseURL: nil)
Will not work. But
someUIWebView.loadHTMLString(HTMLString, baseURL: URL(string: "https://google.com/"))
WILL work, even if your site has nothing to do with google.com.
It appears to me that the Facebook SDK isn't happy with a nil or local/file URL; it needs a genuine HTTP URL.
I have a filebrowser on my server that uses Azure storage to store the files. The website has a feature where when you click on a file, it'll bring up a details window. I use ViewerJS to display a pdf preview of the file (if applicable), and it all works pretty well. The only problem is that when downloading the preview file, you have to reload the preview iframe manually to get it to display. The relevant php function is:
http://pastebin.com/sAyhsbfi
When this function is completed (I'm using ajax), the $.done function calls
response = JSON && JSON.parse(response) || jQuery.parseJSON(response);
$scope.pdfthingy=response; document.getElementById("viewerjs_preview").contentDocument.location.reload(true);
where response on the first line is set to the full pathname to the pdf preview file, and viewerjs_preview is the id of the relevant iframe.
For some reason, this isn't working, and the iframe isn't reloading itself. How do I make it do that when the blob has finished downloading, and pdfthingy is set?
Is the iframe’s domain the same as your host website’s domain? If not, we cannot access its contentDocument (or contentWindow) in host website’s JavaScript code.
To refresh the iframe, per my understanding you can set its src:
document.getElementById('viewerjs_preview').src = document.getElementById('viewerjs_preview').src;
Please note if the src contains a hash tag, we may need additional work. I’d like to suggest you to check What's the best way to reload / refresh an iframe using JavaScript? for more information.
Base on my experience, It is possible that we changed the IFrame URL, but the IFrame showed the preview contents. In this scenario, I suggest you can create the IFarme dynamic. For example, When you got the Blob URI form Azure storage, You could try to remove the Iframe and create a new. For instance, if Your preview content is shown in the iframe as :
<iframe id="viewerjs_preview" src = "/ViewerJS/#../azure blob storage url /pre-blobname .pdf " width='400' height='300' allowfullscreen webkitallowfullscreen></iframe>
You can try to use this code:
function recreateIFM() {
document.getElementById("viewerjs_preview").parentNode.removeChild(document.getElementById("viewerjs_preview"));
var ifm = document.createElement("iframe");
ifm.id = "viewerjs_preview";
ifm.width = "600px";
ifm.height = "400px";
ifm.src = "/ViewerJS/#../azure blob storage url /new-blobname .pdf";
document.body.appendChild(ifm);
}
Also, you can try MingXu's reference about how to refresh/reload the Iframe.
Regards,
Bill_Sww
I find the answer, the major reason is that we shouldn't use controllers to manipulate DOM.
sentence like document.getElementById("viewerjs_preview").contentDocument.location.reload(true) will not work anymore in angular scope, so you have to a directive to do it. I think the same question with you is and which's answer with most votes dose work well.
I think maybe my question was unclear, and for that I apologize. I'll try to go back and edit it tomorrow.
The solution for me was to, rather than set the src attribute of the iframe using angularjs, directly set it with
document.getElementById("iframe-id").src=/path_where_I_put_the_files/filename
(for reference I use "pdfthingy" to store the filename returned by the ajax call that downloads a blob).
This prevented the iframe from loading a null source before the filename was set.
This is perhaps part of why walkformusle has said that DOM should not be controlled in this manner.
I am working on Phonegap application and basically I want to embedd an external webpage inside my html page, yes for me various options are available. I tried with <iframe> method, but I am getting below error:
Refused to display 'https://xyz.com' in a frame because it set 'X-Frame-Options' to 'DENY'
Since I don't have control over the server side, loading an webpage inside an iframe is ruled out.
I also tried with ajax method:
$.ajax({
crossOrigin: true,
url: 'https://xyz.com',
success: function(data) {
$( '#bodyFrame' ).html(data);
}
});
It works fine, but the biggest problem is it doesn't render CSS/Javascript, it only displays plain html.
I tried with <link rel="import" href="https://xyz.com"> now I am getting cross-domain issue.
My question is, is there a way to display an external website inside an HTML page with correct css and js rendering (I don't have control on this part on server side) without IFrame/embed/object tags? I searched lot of questions on SO, most of them tell to use ajax but this have css issue. Can anyone help me in this?
Well, I think that you have at least few options.
Do like I just did for my project where I need to be able to show whole pages offline: load the HTML for that page, iterate through it (with regular expressions) to find out all resource links (JS, CSS, images) and download those (store to file system). Once downloaded, change the URL to URI of your local file on initial HTML. After that show that HTML for user.
Few special things to mention about this way in no particular order:
Implement cache of your own to speed this up.
Use blacklisting for URLs that you don't want to download.
caolan's Async.js library is just great for this.
For CSS resources you need still to download images within it and change the links to those too.
Images can be converted just to Base64 representation inside HTML for less callbacks to handle.
This way you can use the iframes.
This is pretty much related to first one but go through the HTML on your success callback and get all the links for JS and CSS and use technique described here to reload those for you.
Here is summary of that method:
var fileref = document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", filename);
document.getElementsByTagName("head")[0].appendChild(fileref);
Let's say I have download links for files on my site.
When clicked these links send an AJAX request to the server which returns the URL with the location of the file.
What I want to do is direct the browser to download the file when the response gets back. Is there a portable way to do this?
We do it that way:
First add this script.
<script type="text/javascript">
function populateIframe(id,path)
{
var ifrm = document.getElementById(id);
ifrm.src = "download.php?path="+path;
}
</script>
Place this where you want the download button(here we use just a link):
<iframe id="frame1" style="display:none"></iframe>
download
The file 'download.php' (needs to be put on your server) simply contains:
<?php
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$_GET['path']);
readfile($_GET['path']);
?>
So when you click the link, the hidden iframe then gets/opens the sourcefile 'download.php'. With the path as get parameter.
We think this is the best solution!
It should be noted that the PHP part of this solution is a simple demonstration and potentially very, very insecure. It allows the user to download any file, not just a pre-defined set. That means they could download parts of the source code of the site itself, possibly containing API credentials etc.
I have created an open source jQuery File Download plugin (Demo with examples) (GitHub) which could also help with your situation. It works pretty similarly with an iframe but has some cool features that I have found quite handy:
User never leaves the same page they initiated a file download from. This feature is becoming crucial for modern web applications
Tested cross browser support (including mobile!)
It supports POST and GET requests in a manner similar to jQuery's AJAX API
successCallback and failCallback functions allow for you to be explicit about what the user sees in either situation
In conjunction with jQuery UI a developer can easily show a modal telling the user that a file download is occurring, disband the modal after the download starts or even inform the user in a friendly manner that an error has occurred. See the Demo for an example of this.
Just call window.location.href = new_url from your javascript and it will redirect the browser to that URL as it the user had typed that into the address bar
Reading the answers - including the accepted one I'd like to point out the security implications of passing a path directly to readfile via GET.
It may seem obvious to some but some may simply copy/paste this code:
<?php
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$_GET['path']);
readfile($_GET['path']);
?>
So what happens if I pass something like '/path/to/fileWithSecrets' to this script?
The given script will happily send any file the webserver-user has access to.
Please refer to this discussion for information how to prevent this: How do I make sure a file path is within a given subdirectory?
If this is your own server application then i suggest using the following header
Content-disposition: attachment; filename=fname.ext
This will force any browser to download the file and not render it in the browser window.
Try this lib https://github.com/PixelsCommander/Download-File-JS it`s more modern than all solutions described before because uses "download" attribute and combination of methods to bring best possible experience.
Explained here - http://pixelscommander.com/en/javascript/javascript-file-downliading-ignore-content-type/
Seems to be ideal piece of code for starting downloading in JavaScript.
A agree with the methods mentioned by maxnk, however you may want to reconsider trying to automatically force the browser to download the URL. It may work fine for binary files but for other types of files (text, PDF, images, video), the browser may want to render it in the window (or IFRAME) rather than saving to disk.
If you really do need to make an Ajax call to get the final download links, what about using DHTML to dynamically write out the download link (from the ajax response) into the page? That way the user could either click on it to download (if binary) or view in their browser - or select "Save As" on the link to save to disk. It's an extra click, but the user has more control.
To get around the security flaw in the top-voted answer, you can set the iframe src directly to the file you want (instead of an intermediate php file) and set the header information in an .htaccess file:
<Files *.apk>
ForceType application/force-download
Header set Content-Disposition attachment
Header set Content-Type application/vnd.android.package-archive
Header set Content-Transfer-Encoding binary
</Files>
I suggest to make an invisible iframe on the page and set it's src to url that you've received from the server - download will start without page reloading.
Or you can just set the current document.location.href to received url address. But that's can cause for user to see an error if the requested document actually does not exists.
In relation to the top answer I have a possible solution to the security risk.
<?php
if(isset($_GET['path'])){
if(in_array($_GET['path'], glob("*/*.*"))){
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$_GET['path']);
readfile($_GET['path']);
}
}
?>
Using the glob() function (I tested the download file in a path one folder up from the file to be downloaded) I was able to make a quick array of files that are "allowed" to be downloaded and checked the passed path against it. Not only does this insure that the file being grabbed isn't something sensitive but also checks on the files existence at the same time.
~Note: Javascript / HTML~
HTML:
<iframe id="download" style="display:none"></iframe>
and
<input type="submit" value="Download" onclick="ChangeSource('document_path');return false;">
JavaScript:
<script type="text/javascript">
<!--
function ChangeSource(path){
document.getElementByID('download').src = 'path_to_php?path=' + document_path;
}
-->
</script>
I'd suggest window.open() to open a popup window. If it's a download, there will be no window and you will get your file. If there is a 404 or something, the user will see it in a new window (hence, their work will not be bothered, but they will still get an error message).
Why are you making server side stuff when all you need is to redirect browser to different window.location.href?
Here is code that parses ?file= QueryString (taken from this question) and redirects user to that address in 1 second (works for me even on Android browsers):
<script type="text/javascript">
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
(window.onload = function() {
var path = urlParams["file"];
setTimeout(function() { document.location.href = path; }, 1000);
});
</script>
If you have jQuery in your project definitely remove those window.onpopstate & window.onload handlers and do everything in $(document).ready(function () { } );