Processing AJAX result - javascript

I get the javascript file string from ajax, But I can not use the returned javascript string,
I try some way:
1、
tools.get({
url:'/public/dist/page.index.min.js',
success: function(res) {
let blob = new Blob([res])
let url = window.URL.createObjectURL(blob)
let reader = new FileReader()
reader.onload = function(e){
let script = document.createElement('script')
script.src = e.target.result
script.type ='text/javascript'
document.body.appendChild(script)
}
reader.readAsDataURL(blob)
}
})
2、document.write(script_strings)// the script file is compiled by webpack and when render the code in the page, will throw error. like some html tags
3、eval(script_strings)//no use
so Is there any solution to solve the problem..
== added ==
way 1 and way 3: no use and no throw errors
way 2, throw errors, but I can not deal it.
enter image description here

I have solve the problem..
let jscontent = tools.byteToString(tools.base64ToUint8Array(res))
let blob = new Blob([jscontent], { type: "application/javascript;charset=utf-8" })
let url = window.URL.createObjectURL(blob)
let script = document.createElement('script')
script.src = URL.createObjectURL(blob)
script.type ='text/javascript'
document.body.appendChild(script)
and it will load the js content to page.

Related

handle unnamed JSONP in xmlHttpRequest Javascript [duplicate]

Can I make a cross-domain JSONP request in JavaScript without using jQuery or other external library? I would like to use JavaScript itself and then parse the data and make it an object so I could use it. Do I have to use an external library? If not, how can I do it?
function foo(data)
{
// do stuff with JSON
}
var script = document.createElement('script');
script.src = '//example.com/path/to/jsonp?callback=foo'
document.getElementsByTagName('head')[0].appendChild(script);
// or document.head.appendChild(script) in modern browsers
Lightweight example (with support for onSuccess and onTimeout). You need to pass callback name within URL if you need it.
var $jsonp = (function(){
var that = {};
that.send = function(src, options) {
var callback_name = options.callbackName || 'callback',
on_success = options.onSuccess || function(){},
on_timeout = options.onTimeout || function(){},
timeout = options.timeout || 10; // sec
var timeout_trigger = window.setTimeout(function(){
window[callback_name] = function(){};
on_timeout();
}, timeout * 1000);
window[callback_name] = function(data){
window.clearTimeout(timeout_trigger);
on_success(data);
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = src;
document.getElementsByTagName('head')[0].appendChild(script);
}
return that;
})();
Sample usage:
$jsonp.send('some_url?callback=handleStuff', {
callbackName: 'handleStuff',
onSuccess: function(json){
console.log('success!', json);
},
onTimeout: function(){
console.log('timeout!');
},
timeout: 5
});
At GitHub: https://github.com/sobstel/jsonp.js/blob/master/jsonp.js
What is JSONP?
The important thing to remember with jsonp is that it isn't actually a protocol or data type. Its just a way of loading a script on the fly and processing the script that is introduced to the page. In the spirit of JSONP, this means introducing a new javascript object from the server into the client application/ script.
When is JSONP needed?
It is 1 method of allowing one domain to access/ process data from another in the same page asyncronously. Primarily, it is used to override CORS (Cross Origin Resource Sharing) restrictions which would occur with an XHR (ajax) request. Script loads are not subject to CORS restrictions.
How is it done
Introducing a new javascript object from the server can be implemented in many ways, but the most common practice is for the server to implement the execution of a 'callback' function, with the required object passed into it. The callback function is just a function you have already set up on the client which the script you load calls at the point the script loads to process the data passed in to it.
Example:
I have an application which logs all items in someone's home. My application is set up and I now want to retrieve all the items in the main bedroom.
My application is on app.home.com. The apis I need to load data from are on api.home.com.
Unless the server is explicitly set up to allow it, I cannot use ajax to load this data, as even pages on separate subdomains are subject to XHR CORS restrictions.
Ideally, set things up to allow x-domain XHR
Ideally, since the api and app are on the same domain, I might have access to set up the headers on api.home.com. If I do, I can add an Access-Control-Allow-Origin: header item granting access to app.home.com. Assuming the header is set up as follows: Access-Control-Allow-Origin: "http://app.home.com", this is far more secure than setting up JSONP. This is because app.home.com can get everything it wants from api.home.com without api.home.com giving CORS access to the whole internet.
The above XHR solution isn't possible. Set up JSONP On my client script: I set up a function to process the reponse from the server when I make the JSONP call.:
function processJSONPResponse(data) {
var dataFromServer = data;
}
The server will need to be set up to return a mini script looking something like "processJSONPResponse('{"room":"main bedroom","items":["bed","chest of drawers"]}');" It might be designed to return such a string if something like //api.home.com?getdata=room&room=main_bedroom is called.
Then the client sets up a script tag as such:
var script = document.createElement('script');
script.src = '//api.home.com?getdata=room&room=main_bedroom';
document.querySelector('head').appendChild(script);
This loads the script and immediately calls window.processJSONPResponse() as written/ echo/ printed out by the server. The data passed in as the parameter to the function is now stored in the dataFromServer local variable and you can do with it whatever you need.
Clean up
Once the client has the data, ie. immediately after the script is added to the DOM, the script element can be removed from the DOM:
script.parentNode.removeChild(script);
My understanding is that you actually use script tags with JSONP, sooo...
The first step is to create your function that will handle the JSON:
function hooray(json) {
// dealin wit teh jsonz
}
Make sure that this function is accessible on a global level.
Next, add a script element to the DOM:
var script = document.createElement('script');
script.src = 'http://domain.com/?function=hooray';
document.body.appendChild(script);
The script will load the JavaScript that the API provider builds, and execute it.
the way I use jsonp like below:
function jsonp(uri) {
return new Promise(function(resolve, reject) {
var id = '_' + Math.round(10000 * Math.random());
var callbackName = 'jsonp_callback_' + id;
window[callbackName] = function(data) {
delete window[callbackName];
var ele = document.getElementById(id);
ele.parentNode.removeChild(ele);
resolve(data);
}
var src = uri + '&callback=' + callbackName;
var script = document.createElement('script');
script.src = src;
script.id = id;
script.addEventListener('error', reject);
(document.getElementsByTagName('head')[0] || document.body || document.documentElement).appendChild(script)
});
}
then use 'jsonp' method like this:
jsonp('http://xxx/cors').then(function(data){
console.log(data);
});
reference:
JavaScript XMLHttpRequest using JsonP
http://www.w3ctech.com/topic/721 (talk about the way of use Promise)
I have a pure javascript library to do that https://github.com/robertodecurnex/J50Npi/blob/master/J50Npi.js
Take a look at it and let me know if you need any help using or understanding the code.
Btw, you have simple usage example here: http://robertodecurnex.github.com/J50Npi/
/**
* Loads data asynchronously via JSONP.
*/
const load = (() => {
let index = 0;
const timeout = 5000;
return url => new Promise((resolve, reject) => {
const callback = '__callback' + index++;
const timeoutID = window.setTimeout(() => {
reject(new Error('Request timeout.'));
}, timeout);
window[callback] = response => {
window.clearTimeout(timeoutID);
resolve(response.data);
};
const script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = url + (url.indexOf('?') === -1 ? '?' : '&') + 'callback=' + callback;
document.getElementsByTagName('head')[0].appendChild(script);
});
})();
Usage sample:
const data = await load('http://api.github.com/orgs/kriasoft');
I wrote a library to handle this, as simply as possible. No need to make it external, its just one function. Unlike some other options, this script cleans up after itself, and is generalized for making further requests at runtime.
https://github.com/Fresheyeball/micro-jsonp
function jsonp(url, key, callback) {
var appendParam = function(url, key, param){
return url
+ (url.indexOf("?") > 0 ? "&" : "?")
+ key + "=" + param;
},
createScript = function(url, callback){
var doc = document,
head = doc.head,
script = doc.createElement("script");
script
.setAttribute("src", url);
head
.appendChild(script);
callback(function(){
setTimeout(function(){
head
.removeChild(script);
}, 0);
});
},
q =
"q" + Math.round(Math.random() * Date.now());
createScript(
appendParam(url, key, q), function(remove){
window[q] =
function(json){
window[q] = undefined;
remove();
callback(json);
};
});
}
Please find below JavaScript example to make a JSONP call without JQuery:
Also, you can refer my GitHub repository for reference.
https://github.com/shedagemayur/JavaScriptCode/tree/master/jsonp
window.onload = function(){
var callbackMethod = 'callback_' + new Date().getTime();
var script = document.createElement('script');
script.src = 'https://jsonplaceholder.typicode.com/users/1?callback='+callbackMethod;
document.body.appendChild(script);
window[callbackMethod] = function(data){
delete window[callbackMethod];
document.body.removeChild(script);
console.log(data);
}
}
/**
* Get JSONP data for cross-domain AJAX requests
* #private
* #link http://cameronspear.com/blog/exactly-what-is-jsonp/
* #param {String} url The URL of the JSON request
* #param {String} callback The name of the callback to run on load
*/
var loadJSONP = function ( url, callback ) {
// Create script with url and callback (if specified)
var ref = window.document.getElementsByTagName( 'script' )[ 0 ];
var script = window.document.createElement( 'script' );
script.src = url + (url.indexOf( '?' ) + 1 ? '&' : '?') + 'callback=' + callback;
// Insert script tag into the DOM (append to <head>)
ref.parentNode.insertBefore( script, ref );
// After the script is loaded (and executed), remove it
script.onload = function () {
this.remove();
};
};
/**
* Example
*/
// Function to run on success
var logAPI = function ( data ) {
console.log( data );
}
// Run request
loadJSONP( 'http://api.petfinder.com/shelter.getPets?format=json&key=12345&shelter=AA11', 'logAPI' );
If you are using ES6 with NPM, you can try node module "fetch-jsonp".
Fetch API Provides support for making a JsonP call as a regular XHR call.
Prerequisite:
you should be using isomorphic-fetch node module in your stack.
Just pasting an ES6 version of sobstel's nice answer:
send(someUrl + 'error?d=' + encodeURI(JSON.stringify(json)) + '&callback=c', 'c', 5)
.then((json) => console.log(json))
.catch((err) => console.log(err))
function send(url, callback, timeout) {
return new Promise((resolve, reject) => {
let script = document.createElement('script')
let timeout_trigger = window.setTimeout(() => {
window[callback] = () => {}
script.parentNode.removeChild(script)
reject('No response')
}, timeout * 1000)
window[callback] = (data) => {
window.clearTimeout(timeout_trigger)
script.parentNode.removeChild(script)
resolve(data)
}
script.type = 'text/javascript'
script.async = true
script.src = url
document.getElementsByTagName('head')[0].appendChild(script)
})
}

How to provide callback function to iTunes search API

I am struggling to find a way to provide a callback function to correctly use the iTunes Store search API.
I am trying to achieve this behaviour:
const getiTunes = fetch(`https://itunes.apple.com/search?term=${search}&media=movie&limit=200`)
.then(results => results.json())
.then(results => {
if (results.errorMessage) throw Error(results.errorMessage)
else setResults(results)
})
.catch(error => {
//handle error
})
and so far I have this:
const getiTunes = results => {
if (results.errorMessage) throw Error(results.errorMessage)
else setITunes(results)
}
const script = document.createElement("script")
script.src = `https://itunes.apple.com/search?term=${search}&media=movie&limit=200&callback=getiTunes`
script.async = true
document.body.appendChild(script)
I keep getting the following error:
Uncaught ReferenceError: getiTunes is not defined
I have also tried &callback="getiTunes" and &callback=${getiTunes} and they also fail.
These functions are being called in an useEffect hook in React. Is there a specific way I have to retrieve the function name?
Aside
And if I try to not provide a callback function, it will work only if the search is a new search (ie I haven't searched that term before). However, if I have (say on production URL or locally) then it will error with the following:
Access to fetch at 'https://itunes.apple.com/search?term=spiderman&media=movie&limit=200' from origin 'http://localhost:3000' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value "--it has the last URL I used to search for this successfully--"...
The method you're trying is JSONP (JSON with Padding) method. We just need the external script and the a function.
The external website provides a callback function for your method.
So it sends all the data in function parameter.
by mistaken you have adden } to your script url
script.src = `https://itunes.apple.com/search?term=${search}&media=movie&limit=200&callback=getiTunes}`
Eg code:
const getiTunes=results=>{
if (results.errorMessage) throw new
Error(results.errorMessage)
else setITunes(results)
};
const script = document.createElement("script")
script.src = `https://itunes.apple.com/search?term=bat&media=movie&limit=200&callback=getiTunes`
script.async = true
document.body.appendChild(script);
// returns getiTunes(...someData)
I was able to get this working by adding my script to handle the response to the document also.
const loadItunes = document.createElement("script")
loadItunes.src = `https://itunes.apple.com/search?term=${search}&media=movie&limit=200&callback=getiTunes`
loadItunes.async = true
const handleResults = document.createElement("script")
handleResults.type = "text/javascript"
handleResults.text = "function getiTunes(response) { //function code };"
document.body.appendChild(loadItunes)
document.body.appendChild(handleResults)
Updated Answer
I have found a better solution via this code sandbox. It perfectly solves this problem by creating a function which then hands off the response to a callback function.
export const fetchJSONP = (url, callback) => {
var callbackName = "jsonp_callback_" + Math.round(100000 * Math.random())
window[callbackName] = function (data) {
delete window[callbackName]
document.body.removeChild(script)
callback(data)
}
var script = document.createElement("script")
script.src = url + (url.indexOf("?") >= 0 ? "&" : "?") + "callback=" + callbackName
document.body.appendChild(script)
}
I then use it in the following way:
const handleResponse = response => {
//do stuff with response
}
fetchJSONP("https://itunes.apple.com/search?term=spiderman&media=movie&limit=200", handleResponse)

How to pass custom value to existing function (without changing function)?

My angular app has a function (on a different file) that loads a script. I need to load a different script in one case, but utilize the same function. I was told not to touch or add to the existing function but instead "just call it with my values". Not sure what that means exactly :-/
loadScript (url = 'assets/scripts/external/foo.js') {
let body: any = document.getElementsByTagName('body')[0];
let script: any = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
body.appendChild(script);
}
Something like this on my file but I'm thinking but striking out...
url = 'assets/scripts/external/bar.js'
loadScript (this.url);
You can accomplish what your want. I think you're getting thrown off by this:
loadScript (url = 'assets/scripts/external/foo.js')
Whenever you see something like myVar = 'some value' in a function as an argument, that just means it's the default value (if nothing is passed in).
loadScript (url = 'assets/scripts/external/foo.js') {
let body: any = document.getElementsByTagName('body')[0];
let script: any = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
body.appendChild(script);
}
You should be able to call loadScript(<whatever>) and it should work just fine
Simplified example:
function test(myValue = 1) {
return myValue;
}
console.log('Should be 1', test());
console.log('Should be 2', test(2));
So, as you can see, you can accomplish what you want without changing the function at all (assuming you're giving us the full context here)
U can just:
loadScript (var, url = 'assets/scripts/external/foo.js') {
let body: any =
document.getElementsByTagName('body')[0];
let script: any = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
body.appendChild(script);
Console.log(var)
}
You just pass a second argument

How to call a javascript function from external link file in angular 2

I am working on an app with angular 4, and I have a function in javascript to call from my component
The external javascript file is a link file
So To call the javascript file, I did the following code:
const body = <HTMLDivElement> document.body;
const script = document.createElement('script');
script.innerHTML = '';
script.src = 'https://sase.wde.de/dedesa/name.file.js';
script.async = true;
script.defer = true;
script.type = 'text/javascript';
body.appendChild(script);
It works fine until that, then I call the function this way
ngAfterViewInit() {
loadFoo();
}
export default function loadFoo(): void {
const lastname = "dedee";
const firstname = "dede";
const mail = "ede#dede.d";
const mdn = "55662";
const siteweb = "dede.html";
const token = "dededede";
const date = "2018-05-29 14:03:57";
const webPage = "dedesz";
startNAmeNoReg(lastname, firstname, mail, mdn, webPage, token, siteweb, date);
startNAmePush(lastname, firstname, mail, mdn, webPage, token, siteweb, date);
}
When i call the function, it gives me the error
ERROR ReferenceError: startNAmeNoReg is not defined

WebRTC in javascript

I am trying to make WebRTC an object in javascript for easier use.
Since javascript is executed on my side, i get an error saying Firebase is not defined.
So I called the script source using the following code;
///in this section I am trying to get the firebase.js
var head=document.getElementsByTagName('head')[0];
var script=document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', "https://cdn.firebase.com/v0/firebase.js");
head.appendChild(script);
After that I try to get a reference to FireBase database and create my own
var dbRef = new Firebase("https://webrtcdemo.firebaseIO.com/");///this is the line i get the error
var roomRef = dbRef.child("rooms");
To sum up my question is it possible to use WebRTC(reference Firebase) in javascript? If so how is it possible?
Thanks
Since you're loading code from javascript, you need to wait for it to load before continuing:
// define onload handler
function onFirebaseLoad() {
var dbRef = new Firebase("https://webrtcdemo.firebaseIO.com/");
var roomRef = dbRef.child("rooms");
// ...
}
// load the code
var head=document.getElementsByTagName('head')[0];
var script=document.createElement('script');
script.onload = onFirebaseLoad;
script.onreadystatechange = function() {
if(script.readyState == 'complete') onFirebaseLoad();
};
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', "https://cdn.firebase.com/v0/firebase.js");
head.appendChild(script);

Categories

Resources