JS WebAPIs and Website CORS
- 1 Content security policy
- 2 API’s
- 3 Send HTML request with js
- 4 Select element by class or id
- 5 More Complex selector
- 6 Building HTML element through vanilla JS
- 7 Promises, Async, Timeout
- 8 location.hash
- 9 JS for React
- 10 Web apis
- 11 this and bind
- 12 Prototype give pseudo-class functionality to JS functions
1 Content security policy
<meta
http-equiv="Content-Security-Policy"
content="default-src '*'; frame-ancestors http://trialservice.byethost14.com/iplog.php" />
This example explains how this works:
- Site A adds CORS headers to allow site B access to a resource on site A, such as a font.
- Site B can then access that resource due to the CORS header. Without the CORS header, Site B would not be able to access the resource on Site A. View the following pages for further details.
The following requests use CORS.
- Invocations of the XMLHttpRequest or Fetch APIs.
- Web Fonts (for cross-domain font usage in @font-face within CSS).
- WebGL textures.
- Images/video frames drawn to a canvas using drawImage().
- CSS Shapes from images.
By default all servers are same-origin. If we made a button on client that sends a fetch request to some server.
Access to fetch at 'http://server.com/hi.php' from origin 'http://client.com:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Solution add Access-Control-Allow-Origin: http://client.com:8000
to the server response header by modifying the server’s code.
WARN: DO NOT CONFUSE the “cors” “no-cors” parameter in a fetch function. It is effectively meaningless whether you set it or not. All it does is show you an error or not, it will not give the client access to the server resource !
2 API’s
2.1 Audio
let flag = false
const audio = new Audio("https://raw.githubusercontent.com/bleh/bleh.github.io/master/bleh.mp3");
.loop = true;
audiodocument.getElementById("music").addEventListener("click",e=>{
=== false ?
flag .play(), flag = true, e.target.innerText = "playing") :
(audio.pause(), flag = false, e.target.innerText = "paused");
(audio,false) }
2.2 Clipboard
document.addEventListener("click", e=>{
navigator.clipboard.readText().then(
=> document.getElementById("sometextdiv").innerText = clipText);
clipText })
2.3 Broadcast channel
const chan = new BroadcastChannel('test_channel');
.onmessage = function (event) { console.log(event); }
chandocument.getElementById("somebutton").addEventListener("click",e=>{
.postMessage('This is a test message.');
chan })
3 Send HTML request with js
let xmlHttp = new XMLHttpRequest();
.onreadystatechange = function() {
xmlHttpif (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
let response = JSON.parse(xmlHttp.responseText);
document.querySelector("div").innerHTML = response.value.joke;
}
}.open("GET", "https://api.icndb.com/jokes/random/", true);
xmlHttp.send(null); xmlHttp
let responseText = await fetch("https://api.icndb.com/jokes/random/")
It’s nearly impossible to set a promise respone to a variable but much easier with await
let somePromise = fetch("https://api.icndb.com/jokes/random/")
// We still cant do anything with this
let anotherPromise = responseTextPromise.then(response => response.text())
// nope this just returns another promise
let anotheranotherPromise = anotherPromise.then(x => x)
Notice when we use promises, this is no way to send the response to set a variable,
all we can do is infinitely chaining with more .then(..)
which just returns yet another promise
4 Select element by class or id
document.querySelector("#content").value = "new value";
//this will select by id
document.querySelector(".myclass");
//this will select by class
5 More Complex selector
var el = document.querySelector("div.user-panel.main input[name='login']");
<div class="user-panel main">
<input name="login"/>
</div>
6 Building HTML element through vanilla JS
var paragraph = document.createElement("p");
var textContent = document.createTextNode("content");
.appendChild(textContent);
paragraph
document.querySelector("#messages").appendChild(paragraph);
7 Promises, Async, Timeout
sdfs
navigator.geolocation.getCurrentPosition((loc)=>{
return `${loc.coords.latitude} and ${loc.coords.longitude}`
})
//Local storage data is perm
.setItem("key", "someVal");
localStorage.getItem("key");
localStorage
//Session storage data gets deletd on browser close
.setItem("key", "someVal");
sessionStorage.getItem("key"); sessionStorage
8 location.hash
Not the hash function!
Given a url: https://example.com/stuff#blah%20ads%20bah
location.hash
–> #blah%20ads%20bah
decodeURIComponent(location.hash.substr(1))
9 JS for React
- event object
- React uses event as arguments to callbacks a lot
const callback = (e) => {
const domTarget = e.target
console.log(e.type)
}
10 Web apis
- WebUSB Api - connect USB devices
- WebGL - render interactive 3d graphics
- Webassembly - native performance
- Bluetooth Api - Connect to wireless device
- Notification Api - Display system notification
- Service Worker - Caching for offline usage
- Web Workers - Multithread
11 this and bind
this
is an OO construct that allows vision of the outer closure similar toself
in python.this
varys depending on where it is instantiated, assigned or called- On assignment to variable the
context
changeslet a = b
meanscontext
ofb
depends on where this assignment happened.
.bind()
allows us change thecontext
- idiosyncrasy:
const f = ()=>{}
keeps thethis
orcontext
where the function was declared butfunction(){}
does not.
//global context
let dog = {
//dog context
sound : "wolf",
talk : function(){ //note we didnt use arrow notation ()=>{}
console.log(this.sound)
//'this' -> dog context
}
}.talk() // prints wolf
doglet newdogtalk = dog.talk //we basically copied the talk function so
//'this' now points to place of assignment which is global context
newdogtalk() //output undefined since there is no 'sound' in global
let newnewdogtalk = (dog.talk).bind(dog) //bind forces 'this' to point to dog context
newnewdogtalk() //output wolf
11.1 Arrow vs function()
- Arrows binds this to the lexical scope, meaning you can just look at the code and see what encloses the arrow function to understand what
this
points to.- static binding
- function() binds dynamically, meaning
this
depends on how the function is called at run time.- dynamic binding
12 Prototype give pseudo-class functionality to JS functions
JS has a half-baked class system which doesn’t actually have interfaces or abstract methods/classes. All you can do is extend concrete classes with concrete classes.
- JS functions can behave as pseudo-classes
- prototype allows to add methods to this psuedo-classes
- The
clone()
method in typical design pattern is just thenew
method applied to the JS pseudo-class
function Car(name) {
this.name = name;
}.prototype.getName = function(){
Carconsole.log(this.name)
return this.name
}let b = new Car("sick")
.getName() b
const GenericPerson = {
greet() {
console.log(`hello, my name is ${this.name}!`);
,
};
}
function Person(name) {
this.name = name;
}
Object.assign(Person.prototype, GenericPerson);
// or
// Person.prototype.greet = GenericPerson.greet;
to `Person extends GenericPerson` in OOP terms THIS is very similar