Fetch HTTP-resource from an HTTPS-hosted website not working - javascript

This issue is related only to websites hosted on HTTPS, which need to make requests to an HTTP-endpoint (seems to be working in Chrome, however).
The following code was used:
HTML:
<button id="fetchButton">click me</button>
<script>
var worker = new Worker("/worker.js");
var button = document.getElementById("fetchButton");
button.addEventListener("click", function() {
myWorker.postMessage("");
});
worker.onmessage = response => {
console.log("message from worker");
console.log(response.data);
}
</script>
Worker:
onmessage = async function (event) {
const result = await (await fetch("http://localhost:3000/something")).json();
this.postMessage(result);
}
When hosting this website on an HTTPS-enabled website, I get back a response in Chrome, but not in Firefox, but I couldn't find any more specific docs about this one. Is there a way of getting this to work in Firefox, too? Or is this behavior (Firefox) the correct one, on how to deal with mixed-content? The above code works on both Chrome and Firefox, when hosted locally without HTTPS, so it's probably related to serving the website over HTTPS or not.

Related

New text not showing up

I made a Quotes generator website, Which uses an API. When I click Generate Quote it is just stuck on loading
How can I fix it?
function randomQuote(){
quoteBtn.classList.add("loading");
quoteBtn.innerText = "Loading Quote...";
fetch("http://api.quotable.io/random").then(response => response.json()).then(result => {
quoteText.innerText = result.content;
authorName.innerText = result.author;
quoteBtn.classList.remove("loading");
quoteBtn.innerText = "New Quote";
quoteBtn.addEventListener("click", randomQuote);
});
}
Also I get this error which I do not know how to fix
index.js:12 Mixed Content: The page at 'https://mrquoter.netlify.app/' was loaded over HTTPS, but requested an insecure resource 'http://api.quotable.io/random'. This request has been blocked; the content must be served over HTTPS.
Also when I run it on my local server it runs fine, But I hosted it on netlify.app and it gives out an error
Use a secure endpoint: https://api.quotable.io/random
Perhaps use async/await to make your code easier to parse.
Keep the button outside of the element you're updating.
const button = document.querySelector('button');
const quote = document.querySelector('.quote');
const endpoint = 'https://api.quotable.io/random';
button.addEventListener('click', handleClick, false);
async function handleClick() {
const response = await fetch(endpoint);
const data = await response.json();
quote.textContent = data.content;
}
.quote { margin-top: 1em; }
<button>New quote</button>
<div class="quote"></div>
You can not mix loading resources from HTTP sources when you have a HTTPS website because it alters the behavior of your HTTPS website (i.e. a secure website is not secure anymore) which opens up for new attack vectors on your HTTPS website as described here.
You simply need to change the query URL to
'https://api.quotable.io/random'
As your website uses HTTPs but you are calling the API with HTTP
HTTPs is a secure version of HTTP
You can find more about HTTP & HTTPs Here

MediaDevices: devicechange event not working on ubuntu server

I am using MediaDevices: devicechange event in my react application. On local machin all working good but when i deployed application on server (ubuntu) it gives me the following error
The only difference is OS on local machine I use windows but server is ubuntu.
Here is my function
export function useDevices() {
const [devices, setDevices] = useState<MediaDeviceInfo[]>([]);
useEffect(() => {
const getDevices = () => navigator.mediaDevices.enumerateDevices().then(devices => setDevices(devices));
navigator.mediaDevices.addEventListener('devicechange', getDevices);
getDevices();
return () => {
navigator.mediaDevices.removeEventListener('devicechange', getDevices);
};
}, []);
return devices;
}
Thanks in advance.
I found the answer here getUserMedia() is no longer supported in chrome browser over http:// (Unsecure Origin) , It will work on https:// (Secure Origin)
For testing purposes, You can run chrome with the --unsafely-treat-insecure-origin-as- for this, you need to visit this link in chrome chrome://flags/#unsafely-treat-insecure-origin-as-secure and enable the option, add your site URL in the text area, and relaunch the browser. Now you should able to use getmediadevices method.

JavaScript HTTP Request Not in Incognito Mode

I'm new to web development and am trying to build a small webpage that'll attempt to detect if anyone's currently logged into Instagram on that browser. If I run my code command-by-command in Chrome's console and manually copy-paste the HTML, it works perfectly. But when I try to run my code separately, it seems to run as if it was in Incognito mode.
How would one get around this? If the user needs to grant my page permission to access Instagram, how would I do that?
Here's the JS part of my code:
const USERNAME_REGEX = /"viewer"\:{.*"full_name"\:"([^"]+)"/gm;
const FULLNAME = 'full_name\":\"';
document.addEventListener('DOMContentLoaded', () => {
const request = new XMLHttpRequest();
request.open('GET', 'https://instagram.com');
request.send();
request.onload = () => {
const data = request.responseText;
var u = data.match(USERNAME_REGEX);
if (u != null) {
u = u[0];
u = u.substring(u.indexOf(FULLNAME) + FULLNAME.length).slice(0, -1);
document.querySelector('#info').innerHTML = u;
}
else {
document.querySelector('#info').innerHTML = 'no one is logged in!';
}
}
});
Thank you :) have a wonderful day!
I'm new to web development and am trying to build a small webpage that'll attempt to detect if anyone's currently logged into Instagram on that browser.
That sounds like a security and privacy nightmare, which fortunately for everyone (you included) isn't possible. (Or at least, it shouldn't be...)
If I run my code command-by-command in Chrome's console and manually copy-paste the HTML, it works perfectly.
Totally different context. You'll find, in fact, that if you run this code in a console that isn't on Instagram.com, it won't work.
Same-origin policy will prevent you from accessing another domain. What you're attempting is a classic cross-origin attack that isn't going to work. CORS would get around this, but Instagram surely isn't going to enable you access.
How would one get around this?
You don't.

DOM Exception 11 on XHR request occurring only in Safari

I have a very simple function that downloads chunks of a file using an xhr request that looks like so:
var blobXHR = new XMLHttpRequest();
//api.media.chunkURL() returns the correct URL for each chunk
blobXHR.open("GET", api.media.chunkURL({
fileId: fileID,
chunkId: chunkNumber
}));
blobXHR.responseType = "arraybuffer";
blobXHR.onerror = function (e) {
console.log("Error: ", e);
};
var arrayBuffer;
blobXHR.onload = function (e) {
arrayBuffer = blobXHR.response;
};
blobXHR.send();
Now this download function works without any hitches at all using Chrome, Firefox, and just about every Android browser. Unfortunately, when using anything Safari or iOS based I get a very vague error in blobXHR.onerror(). When I output this error to the console I get this response under "e.currentTarget.responseText":
Error: InvalidStateError: DOM Exception 11
I've looked up many questions similar to this and nothing has seemed to work. Any reason why I would be experiencing this with only Safari/iOS browsers?
Edit: This is what I get when I console.log(blobXHR) within onerror():
This is likely a CORS issue. Make sure your server is properly configured to allow this:
http://enable-cors.org/server.html
Also be mindful that Safari won't allow localhost for CORS.

Immediate Disconnection using websocket in FireFox Addon

I've been working on browser extensions that interact with a local application running a WebSocket server.
Safari and Chrome Extensions were very easy to implement, and after some headache getting a feel for FF development, I thought I would be able to implement WebSockets as I had in the other browsers. However I have had some issues.
I understand that I can't directly create a WebSocket in the "main" js file, and so attempted to use workarounds I found on the internet:
https://github.com/canuckistani/Jetpack-Websocket-Example uses a page-worker as a sort of proxy between main and the WebSocket code. When I implement this code, my WebSocket connection immediately errors w/ {"isTrusted":true} as the only information.
I also tried to use a hiddenframe as it appears this is how 1Password deals with websocket communication in their FF Addon, but this also results in the same immediate error.
When I simply open a websocket connection to my server in my normal FF instance, it connects perfectly, but so far, I haven't gotten anything to work from addon.
making pageWorker with:
var pw = pageWorker.Page({
contentUrl: self.data.url('com.html'),
contentScriptFile: self.data.url('com.js')
})
com.html:
<!DOCTYPE HTML>
<html>
<body>
</body>
</html>
com.js:
document.onready = launchCom();
// Could this need to be on ready?
function launchCom() {
console.log("[com.js] launchCom Called");
var wsAvailable = false;
if ("WebSocket" in window) {
console.log("[com.js] Detected Websocket in Window, attempting to open...");
// WebSocket is supported.
ws = new WebSocket('ws://localhost:9001');
wsAvailable = true;
} else {
console.log("[com.js] Websocket is not supported, upgrade your browser!");
}
}
ws.onmessage = function(event) {
console.log(event.data);
}
ws.onopen = function(evt) {
console.log("[com.js] ws opened. evt: " + evt);
}
ws.onerror = function(evt) {
console.log("[com.js] ws error: " + JSON.stringify(evt));
}
Running this results in:
console.log: xxx: [com.js] launchCom Called
console.log: xxx: [com.js] Detected Websocket in Window, attempting to open...
console.log: xxx: [com.js] ws error: {"isTrusted":true}
console.log: xxx: [com.js] ws closed. evt: {"isTrusted":true}
Any help would be greatly appreciated!
I've solved the problem:
I'm using https://github.com/zwopple/PocketSocket in my OS X application as my server, and there appears to be an issue with PocketSocket and FF.
After changing PocketSocket's PSWebSocketDriver.m line 87 code from
[[headers[#"Connection"] lowercaseString] isEqualToString:#"upgrade"]
to
[[headers[#"Connection"] lowercaseString] containsString:#"upgrade"]
per https://github.com/zwopple/PocketSocket/issues/34,
I was able to open a WebSocket connection from FF addon using the original code, but the server errored on messages.
Setting network.websocket.extensions.permessage-deflate to false in about:config allowed messages to be sent so I added
require("sdk/preferences/service").set("network.websocket.extensions.permessage-deflate", false);
to my main.js and everthing is working!
The tiny change to PocketSocket's code hasn't had any effects on the server interacting with other WebSocket clients.
I also got stuck in similar situation as websocket can't be implemented directly in main.js. I also did the same as you did , may be server is refusing connection. Snippet from my code look like below :
main.js
var wsWorker = require('sdk/page-worker').Page({
contentURL: "./firefoxScript/webSocket.html",
contentScriptFile : ["./firefoxScript/webSocket.js"]
});
webSocket.html
<html>
<head>
<title></title>
</head>
<body>
</body>
</html>
webSocket.js
var ws = new WebSocket('ws://localhost:9451');
ws.onopen = function() {
console.log('Connection open...');
};
ws.onclose = function() {
console.log('Connection closed...');
};
ws.onmessage = function(event) {
console.log('Message recieved...');
};
ws.onerror = function(event) {
console.log('Connection Error...');
};
It's perfectly working fine for me.

Categories