What is the best way to download a dynamically created zip file using AngularJS? I can hit the URL using window.open, but this seems very un-Angular, I could use an iframe, but I don't know how I would get a reference to it in my RestService.
What would be a good Angular implementation to allow for downloading of dynamically created files?
// Current solution
RestService.createInstance( data )
.then(function( id) {
//return RestService.generateArchive( id );
var url = location.href;
if( url.indexOf('#') != -1 ) { url = url.substring(0, url.indexOf('#')); }
url += '?ID=' + id;
window.open( url );
})
.then(function( success ) {
// Obviously won't work due to security
});
Also, how would you check if the response was rejected? Seems like you can't, but just in case.
Small sample :
Html :
<iframe ng-src="{{url}}" style="display:none"/>
JS:
$scope.url = 'google.com';
RestService.createInstance( data )
.then(function( id) {
//return RestService.generateArchive( id );
var url = location.href;
if( url.indexOf('#') != -1 ) { url = url.substring(0, url.indexOf('#')); }
url += '?ID=' + id;
$scope.url = $sce.trustAsResourceUrl(url);
})
This should work some remarks :
ofcourse don't forget to inject $sce
If you download multiple times from the same url, reset the url between downloads to something like google.com
Related
I'm trying to reuse a button in different landing pages and change the hyperlink of this button depending on what page is being browsed.
I started my function for it but I'm stuck on how to pass the data. If the user is on a page that contains home_ns in the url, I would like the button link to be cart1 and if the user is on a page called home_nd I would like it to be cart 2.
<script type="text/javascript">
var cart1 = '/?add-to-cart=2419';
var cart2 = '/?add-to-cart=2417';
function urlCart() {
if(window.location.href.indexOf("home_ns") > -1) {
// This is where I am stuck
}
}
</script>
Then the button will be
<button onclick="urlCart()">Order Now</button>
Here is what you need:
var cart1 = '/?add-to-cart=2419';
var cart2 = '/?add-to-cart=2417';
function urlCart() {
if(window.location.href.indexOf("home_ns") > -1) {
window.location.href = cart1;
} else {
window.location.href = cart2;
}
}
You could create a look-up map of pages to cart ID. You can then update the search parameter in the URL to reflect the found ID.
Note: Since the Stack snippet below is not going to actually have the correct href, the code will not add/update the parameter. If you want to integrate this, replace the url variable declaration with this:
let url = window.location.href;
You could also use the pathname instead of the href for finer granularity.
let url = window.location.pathname;
// See: https://stackoverflow.com/a/56593312/1762224
const setSearchParam = function(key, value) {
if (!window.history.pushState) return;
if (!key) return;
let url = new URL(window.location.href);
let params = new window.URLSearchParams(window.location.search);
if (value === undefined || value === null) params.delete(key);
else params.set(key, value);
url.search = params;
url = url.toString();
window.history.replaceState({ url: url }, null, url);
}
const pageMap = {
"home_ns": 2419,
"home_nd": 2417
};
function urlCart() {
let url = 'https://mywebsite.com/home_ns' || window.location.href;
Object.keys(pageMap).some(page => {
if (url.includes(page)) {
console.log('Found page:', page);
setSearchParam('add-to-cart', pageMap[page]);
return true;
} else {
return false;
}
});
}
<button onclick="urlCart()">Order Now</button>
Simply you can move the user to another page by:
location.href = myURL;
The browser will automatically go to the specified page.
Examples of what a URL can be:
An absolute URL - points to another web site (like
location.href="http://www.example.com/default.htm")
A relative URL - points to a file within a web site (like location.href="default.htm")
An anchor URL - points to an anchor within a page (like
location.href="#top")
A new protocol - specifies a different protocol
(like location.href="ftp://someftpserver.com",
location.href="mailto:someone#example.com" or
location.href="file://host/path/example.txt")
Source
I Am Using history.pushState Method Which Change My URL and Title
window.history.pushState(null, response.pageTitle, curl);
using this : Change Meta Tag Description and Keyword
$('meta[name="description"]').attr('content', d.meta_disc_program);
$('meta[name="keywords"]').attr('content', d.meta_keyword_program);
URL | Meta Tag | Title Change dynamic by Database.
on page load or refresh - data get by match URL with database URL Field.
All work good in page.
But in View Source : URL Change But Not Show Any Meta Tag | Title in View Source
Explain More My Question :
This is Dummy code Which i used - d.ProgramUrlonWeb is (like : /b-tech-Electrical-engineering) it generate curl(see on code)
//Change URL
if (d.ProgramUrlonWeb) {
var ma = window.document.URL;
var res = ma.substring(0, ma.indexOf('\search-your-course'));
if (ma.indexOf('\search-your-course') != -1 && data.length > 0) {
if (d.ProgramUrlonWeb != null && d.ProgramUrlonWeb != undefined) {
//back slash in url
if (ma.indexOf('localhost') != -1) {
curl = res + 'search-your-course/programmes' + d.ProgramUrlonWeb;
}
}
}
else {
if (d.ProgramUrlonWeb != null && d.ProgramUrlonWeb != undefined) {
//forward slash in url
if (ma.indexOf('localhost') != -1 || ma.indexOf('admission.aksuniversity.ac.in') != -1) {
curl = 'search-your-course/programmes' + d.ProgramUrlonWeb;
}
}
}
//window.location.href="#";
//dynamic url
var response = {};
var stateObj = {};
response.pageTitle = d.meta_title_program;
processAjaxData(response, stateObj, ma + curl);
$('meta[name="description"]').attr('content', d.meta_disc_program);
$('meta[name="keywords"]').attr('content', d.meta_keyword_program);
}
//Change URL
Next step : processAjaxData Change Page Title and URL by using window.history.pushState.
function processAjaxData(response, stateObj, urlPath) {
var Title = response.pageTitle;
if (urlPath != "" && urlPath != undefined) {
window.history.pushState(null, response.pageTitle, curl);
document.title = Title;
}
}
on Page reload : Match URL (like : /b-tech-Electrical-engineering) in database and return the all field of data base like meta tag and page data etc.
Problem: All Work in page also work refresh in page but when i open view source Not Work All Field is empty. So any solution ?.
demo link which i want .
Thanks, View Source is load data server side, so the solution is to load some data which are important for SEO in server-side.
I am generating some server-side code like meta title and description and keyword and heading tag which is important for SEO. change some code - load Important SEO content before the page loads.
match URL by the database (PHP) return some SEO Tag and heading which is work in view source. I hope I am used current strategy.
I'm trying to get the source code form a URL web page using JSONP.
This is the code:
<script type="text/javascript">
var your_url = '';
$(document).ready(function(){
jQuery.ajax = (function(_ajax){
var protocol = location.protocol,
hostname = location.hostname,
exRegex = RegExp(protocol + '//' + hostname),
YQL = 'http' + (/^https/.test(protocol)?'s':'') + '://query.yahooapis.com/v1/public/yql?callback=?',
query = 'select * from html where url="{URL}" and xpath="*"';
function isExternal(url) {
return !exRegex.test(url) && /:\/\//.test(url);
}
return function(o) {
var url = o.url;
if ( /get/i.test(o.type) && !/json/i.test(o.dataType) && isExternal(url) ) {
// Manipulate options so that JSONP-x request is made to YQL
o.url = YQL;
o.dataType = 'json';
o.data = {
q: query.replace(
'{URL}',
url + (o.data ?
(/\?/.test(url) ? '&' : '?') + jQuery.param(o.data)
: '')
),
format: 'xml'
};
// Since it's a JSONP request
// complete === success
if (!o.success && o.complete) {
o.success = o.complete;
delete o.complete;
}
o.success = (function(_success){
return function(data) {
if (_success) {
// Fake XHR callback.
_success.call(this, {
responseText: data.results[0]
// YQL screws with <script>s
// Get rid of them
.replace(/<script[^>]+?\/>|<script(.|\s)*?\/script>/gi, '')
}, 'success');
}
};
})(o.success);
}
return _ajax.apply(this, arguments);
};
})(jQuery.ajax);
$.ajax({
url: your_url,
type: 'GET',
success: function(res) {
var text = res.responseText;
//document.getElementById("contenuto").innerHTML = text;
alert(text);
}
});
});
</script>
I printed with an alert all the source code, from the URL.
alert(text);
First, how to know if the printed code is all the web code of the page?
If I try to do in this way
document.getElementById("contenuto").innerHTML = text;
this is the result:
\ \ <'+'/ins>\ \ \ '); } ]]>
I tried to use HTML DOM to print just one element, doing in this way
document.getElementById("contenuto").innerHTML = text;
var elem = text.getElementById("strip_adv").innerHTML;
document.getElementById("contenuto_1").innerHTML = elem;
}
But this is the error on the JS console:
text.getElementById is not a function
Recap:
I would to get the source code of a web page from URL, using JSONP.
I would use HTML DOM from the returned text, to keep only the element/class I need. I'm a newbie on JS, I'm trying to learn more & more about JS.
getElementById() is present only in the document object. What you are trying to do is trying to access getElementId from a string object.
Instead what I would suggest is insert the returned html string inside iframe and you can access the elements within iframe otherwise you can use some kind of html parser in your application.
lets say your html looks like this after you insert your html string inside iframe
<body>
<iframe id="one">
<html>
<body> <h1 id="strip_adv">Heading</h1> </body>
</html
</iframe>
</body>
function iframeObj( frameEle ) {
return frameEle.contentWindow
? frameEle.contentWindow.document
: frameEle.contentDocument
}
var element = iframeObj( document.getElementById('strip_adv') );
I'm trying to change the URL in the address bar using javascript.
So if the user access the page using
www.example.com/ajax/project8.html
Url should be changed automatically to
www.examp.com/#cbp=ajax/project8.html
shouldn't be any harder than this:
window.location = "http://whatever.you.want.com"
UPDATE
So you want your site to redirect to another page when the url is www.example.com/ajax/project.aspx?id=whatever and id=xxx could be any id.
To achieve that you need a function that returns the query string parameter value eg:id=whatever
Then check if the current url needs to be redirected to another page. If this is the case then redirect to new url with same parameter value.
/*
function that returns a query string parameter value
this function works with many parameters
Eg: www.example.com/#cbp=ajax/project.aspx?myParam=hello&id=1283&otherParam=234
to get the param value just give it the parameters name
getQueryStringValue("id") returns : 1283
getQueryStringValue("myParam") returns : "hello"
*/
function getQueryStringValue( name ){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
//current url
var currentUrl = location.href;
//check if current url contains www.example.com/ajax/project.aspx
if (currentUrl.indexOf("www.example.com/ajax/project.aspx") != -1 ){
//new url for redirection
var newUrl = "www.example.com/#cbp=ajax/project.aspx?id=" + getQueryStringValue( "id" );
//redirect to new page
location.href = newUrl;
}
Try this code
if (window.location.href == 'www.example.com/ajax/project8.html') {
window.location = 'www.examp.com/#cbp=ajax/project8.html';
}
you can set all things like
window.location.href = "www.examp.com/#cbp=ajax/project8.html"
for more details how you will manage all url parameter then please see
JavaScript and jQuery url managment
window.location.href = "#cbp=ajax/project8.html";
you can change the value written after # to any location , div id etc.
e.g
window.location.href = "#myDivID";
<meta http-equiv="refresh" content="0; url=http://example.com/" />
Note: please put on header
or
<script type="text/javascript">
window.location.assign("http://www.example.com")
</script>
I've found similar questions but none of the answers show clearly and easily how to get a thumbnail for a vimeo video using jQuery and JSON. If anyone can help that would be great, here is what I've got but it shows nothing at the moment.
var vimeoVideoID = '17631561';
var videoCallback = 'showThumb';
$.getJSON('http://www.vimeo.com/api/v2/video/' + vimeoVideoID + '.json?callback=' + videoCallback,
function(data){
$(".thumbs").attr('src',data[0].thumbnail_large);
});
Thanks in advance.
I believe you're having the "same origin policy" issue. You should consider writing a server side script using something like "file_get_contents" or "fopen", enabling you to grab the data from vimeo, translate it to json, and output to your javascript with a nice ajax call.
If you would like to avoid using a server-side script you may use the data type JSONP.
var vimeoVideoID = '17631561';
$.getJSON('https://www.vimeo.com/api/v2/video/' + vimeoVideoID + '.json?callback=?', {format: "json"}, function(data) {
$(".thumbs").attr('src', data[0].thumbnail_large);
});
Notice the URL is a bit different from how you are using it. The callback which you defined as a var is unnecessary. You're attaching the getJSON to a function directly, so you'll call the 'callback' in the url '?'. This informs the getJSON function to pass the successful data return to the supplied function.
You can test my code here. Hope it helps!
With the updated API, it would be...
$.getJSON('https://vimeo.com/api/oembed.json?url=https://vimeo.com/' + id, {format: "json"}, function(data) {
$(".thumbs").attr('src', data.thumbnail_url)
});
You can use this function which supports all types of Vimeo links & sizes:
function get_vimeo_thumbnail(url, size, callback)
{
var result;
if(result = url.match(/vimeo\.com.*[\\\/](\d+)/))
{
var video_id = result.pop();
if(size == 'small'){
var video_link = encodeURIComponent("https://vimeo.com/" + video_id + "?width=480&height=360");
$.getJSON('https://vimeo.com/api/oembed.json?url=' + video_link, function(data) {
if(data && data.thumbnail_url){
if (typeof(callback) !== 'undefined') {
callback(data.thumbnail_url);
}
}
});
}
else
{
$.getJSON('http://vimeo.com/api/v2/video/' + video_id + '.json', function(data) {
if(data){
if (typeof(callback) !== 'undefined') {
var thumbnail_src = data[0].thumbnail_large;
if(thumbnail_src){
callback(thumbnail_src);
}
}
}
});
}
}
}
To use it:
// Available sizes: large, small
get_vimeo_thumbnail('https://vimeo.com/475772381', 'large' function(url){
alert(url)
})
Please check out this page; Vimeo has a new method call oEmbed as Vimeo is now pushing it's new oEmbed technology.
The method above, will fail on IE (no thumbs will be shown).