Access to XMLHttpRequest at 'https://domainname.com/signalr/negotiate?clientProtocol=2.1&connectionData=%5B%7B%22name%22%3A%22notificationhub%22%7D%5D&_=1654470068390' from origin 'https://domainname.com' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
this is my Hub Api server startup code
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
EnableJavaScriptProxies = true
};
map.RunSignalR(hubConfiguration);
});
this is my hub code
public class NotificationHub : Hub
{
public void Hello(string msg)
{
Clients.All.hello(msg);
}
public void JoinToArea(string name)
{
}
public override Task OnConnected()
{
var id = Context.ConnectionId;
return base.OnConnected();
}
}
this is my client code
<script src="~/Scripts/jquery.signalR-2.4.3.js"></script>
<script src="https://localhost:44312/signalr/hubs"></script>
<script>
$(document).ready(function () {
Connect();
});
var stockTickerHubProxy;
function Connect() {
$.connection.hub.url = 'https://localhost:44312/signalr';
stockTickerHubProxy = $.connection.notificationHub;
stockTickerHubProxy.client.foo = function () { };
stockTickerHubProxy.client.hello = function (msg) {
alert(msg);
}
if (stockTickerHubProxy) {
$.connection.hub.start().done(function () {
console.log("Connected...");
connectionId = $.connection.hub.id;
console.log(connectionId)
stockTickerHubProxy.server.joinToArea("OK");
stockTickerHubProxy.client.hello = function (msg) {
alert(msg);
}
})
.fail(function () {
alert("Can't connect");
})
;
$.connection.hub.disconnected(function () {
console.log("Server disconnected.");
});
$.connection.hub.reconnecting(function () {
console.log("Server reconnecting...");
});
$.connection.hub.reconnected(function () {
console.log("Server reconnected...");
Connect();
});
$.connection.hub.error(function (error) {
console.log('SignalR error: ' + error)
});
}
}
</script>
this work fine on localhost when i give hub api server host domain URL its generate this error. how can i fix this issue .
Related
I'm trying to have a service worker intercept fetch requests coming from a client-side SvelteKit load function. The network requests are being made, but the fetch event is not being triggered.
The fetch request from the load function is going to /api/allTeams, which is cached as reported by chrome devtools, but like I said, it's not getting intercepted. All the function does it fetch the data, and return it in a prop.
Also, every couple minutes I run invalidateAll(), to reload the data, and even those requests aren't being picked up by the SW.
Thanks!
--reese
src/service-worker.js:
import { build, version } from '$service-worker';
self.addEventListener('fetch', function (event) {
console.log("fetch")
event.respondWith(
fetch(event.request).catch(function () {
return caches.match(event.request);
}),
);
});
self.addEventListener('install', async function (event) {
event.waitUntil(
caches.open("ccs-" + version).then(function (cache) {
cache.add("/api/allTeams")
cache.addAll(build)
return;
}),
);
});
src/app.html:
<script>
const registerServiceWorker = async () => {
if ("serviceWorker" in navigator) {
try {
const registration = await navigator.serviceWorker.register("/service-worker.js", {
scope: "*",
});
if (registration.installing) {
console.log("Service worker installing");
} else if (registration.waiting) {
console.log("Service worker installed");
} else if (registration.active) {
console.log("Service worker active");
}
} catch (error) {
console.error(`Registration failed with ${error}`);
}
}
};
registerServiceWorker()
</script>
src/+page.ts:
export async function load(request: Request) {
const searchQuery = new URL(request.url).searchParams.get("q")
const apiUrl = new URL(request.url)
apiUrl.pathname = "/api/allTeams"
const req = await fetch(apiUrl)
const data = await req.json()
return {data, searchQuery};
}
I want a grails application in which server sends some message at a fixed interval.
I have tried using spring-websocket plugin in grails, server and client are able to connect but that doesn't fullfill my requirement. i.e., I want, server sends some message at a fixed interval.
This is the server-side code :
package test
import org.springframework.messaging.handler.annotation.MessageMapping
import org.springframework.messaging.handler.annotation.SendTo
class ExampleController {
def index() { }
// server
#MessageMapping("/hello")
#SendTo("/topic/hello")
protected String hello(String world) {
List<String> list = new ArrayList<>();
BufferedReader file = new BufferedReader(new FileReader("src/main/resources/dummyLog.txt"));
file.eachLine {line ->
list.add(line)
}
int idx = (int)(Math.random() * list.size());
println idx;
return list.get(idx);
}
}
And this is the client-side code :
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', () => {
var socket = new SockJS("${createLink(uri: '/stomp')}");
var client = webstomp.over(socket);
client.connect({}, function() {
client.subscribe("/topic/hello", (message) => {
document.getElementById('helloDiv').append(message.body);
});
});
document.getElementById('helloButton').addEventListener('click', () => {
client.send("/app/hello", JSON.stringify("world"));
});
});
</script>
Thanks.
PeerJS: 1.3.2
Tested on: iOS 15 & 13.
I have the below call service file that implements PeerJS functionality to init, establish and answer video calls.
Calls work as expected across Android devices, macOS and PCs.
However, when attempting to join from an iOS device, we see the following error raised:
NotAllowedError: The request is not allowed by the user agent
or the platform in the current context, possibly because the
user denied permission.
call-service.js:
import { Injectable } from '#angular/core';
import { MatSnackBar } from '#angular/material/snack-bar';
import Peer from 'peerjs';
import { BehaviorSubject, Subject } from 'rxjs';
import { v4 as uuidv4 } from 'uuid';
#Injectable()
export class CallService {
private peer: Peer;
private mediaCall: Peer.MediaConnection;
private localStreamBs: BehaviorSubject<MediaStream> = new BehaviorSubject(null);
public localStream$ = this.localStreamBs.asObservable();
private remoteStreamBs: BehaviorSubject<MediaStream> = new BehaviorSubject(null);
public remoteStream$ = this.remoteStreamBs.asObservable();
private isCallStartedBs = new Subject<boolean>();
public isCallStarted$ = this.isCallStartedBs.asObservable();
constructor(private snackBar: MatSnackBar) { }
public initPeer(): string {
if (!this.peer || this.peer.disconnected) {
const peerJsOptions: Peer.PeerJSOption = {
debug: 3,
config: {
iceServers: [
{
urls: [
'stun:stun1.l.google.com:19302',
'stun:stun2.l.google.com:19302',
],
}]
}
};
try {
let id = uuidv4();
this.peer = new Peer(id, peerJsOptions);
return id;
} catch (error) {
console.error(error);
}
}
}
public async establishMediaCall(remotePeerId: string) {
try {
const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true});
let peerOptions: any = {};
if (this.checkSafari()) {
peerOptions.serialization = "json";
}
const connection = this.peer.connect(remotePeerId, peerOptions);
connection.on('error', err => {
console.error(err);
this.snackBar.open(err, 'Close');
});
this.mediaCall = this.peer.call(remotePeerId, stream);
if (!this.mediaCall) {
let errorMessage = 'Unable to connect to remote peer';
this.snackBar.open(errorMessage, 'Close');
throw new Error(errorMessage);
}
this.localStreamBs.next(stream);
this.isCallStartedBs.next(true);
this.mediaCall.on('stream',
(remoteStream) => {
this.remoteStreamBs.next(remoteStream);
});
this.mediaCall.on('error', err => {
this.snackBar.open(err, 'Close');
console.error(err);
this.isCallStartedBs.next(false);
});
this.mediaCall.on('close', () => this.onCallClose());
}
catch (ex) {
console.error(ex);
this.snackBar.open(ex, 'Close');
this.isCallStartedBs.next(false);
}
}
public async enableCallAnswer() {
try {
let peerOptions: any = {};
if (this.checkSafari()) {
peerOptions.serialization = "json";
}
const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
this.localStreamBs.next(stream);
this.peer.on('call', async (call) => {
this.mediaCall = call;
this.isCallStartedBs.next(true);
this.mediaCall.answer(stream);
this.mediaCall.on('stream', (remoteStream) => {
this.remoteStreamBs.next(remoteStream);
});
this.mediaCall.on('error', err => {
this.snackBar.open(err, 'Close');
this.isCallStartedBs.next(false);
console.error(err);
});
this.mediaCall.on('close', () => this.onCallClose());
});
}
catch (ex) {
console.error(ex);
this.snackBar.open(ex, 'Close');
this.isCallStartedBs.next(false);
}
}
private onCallClose() {
this.remoteStreamBs?.value.getTracks().forEach(track => {
track.stop();
});
this.localStreamBs?.value.getTracks().forEach(track => {
track.stop();
});
this.snackBar.open('Call Ended', 'Close');
}
public closeMediaCall() {
this.mediaCall?.close();
if (!this.mediaCall) {
this.onCallClose()
}
this.isCallStartedBs.next(false);
}
public destroyPeer() {
this.mediaCall?.close();
this.peer?.disconnect();
this.peer?.destroy();
}
public checkSafari() {
let seemsChrome = navigator.userAgent.indexOf("Chrome") > -1;
let seemsSafari = navigator.userAgent.indexOf("Safari") > -1;
return seemsSafari && !seemsChrome;
}
}
Closing. This was a local permissions issue on my test device and no fault of PeerJS.
Reinstalling Chrome on iOS then enabled the relevant camera permissions
I have implemented SignalR in my application and it worked fine in On-prem, once I publish it in Azure Gov SignalR call from server to client is not working always. Especially with IE brewer SignalR calls are not working for most of the times. In Chrome sometimes it is not working
Client Code
$(function () {
var ccuHub = $.connection.alertHub;
$.connection.hub.logging = true;
$.connection.hub.start().done(function () { }).fail(function (error) {
console.log('start error: ' + error);
});
if (window.location.pathname == baseUrl + "Home/UserLogin" && $('#inpHdnUserconcurrentUserID').val() != undefined) {
concurrentUserId = $('#inpHdnUserconcurrentUserID').val();
}
ccuHub.client.ForceLogOut = function (connectionId) {
if (connectionId != concurrentUserId) {
// alert('Not Matched concurrentUserId' + concurrentUserId);
Utility.showMessage(resourceList.ConcurrentUser_Warning_SameUserLoggedInAnother, Utility.MessageType.Warning);
var onSuccessLoginLogOut = function () {
window.location.href = baseUrl + "Login/Index?returnUrl=Y"
};
Utility.makeAjaxCall("Login/Logout", "POST", JSON.stringify({ concurrentUserID: concurrentUserId }), onSuccessLoginLogOut, null, null, false);
//$.connection.hub.stop();
}
};
});
Server Code
[HttpGet]
public void ConcurrentUserLogOut(string connectionId)
{
try
{
logger.Info($"ConcurrentUserLogOut-ConnectionID:{connectionId}");
IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<AlertHub>();
hubContext.Clients.All.ForceLogOut(connectionId);
}
catch (Exception ex)
{
logger.Error("Error on ConcurrentUserLogOut , connection Id : " + connectionId + " Error :" + ex.Message, ex);
}
}
Is there anything need to done specially for Azure? Also SignalR methods are taking too much of time in Azure, app become very slow.
How to resolve(or hide) Uncaught (in promise) DOMException: Quota exceeded error in service worker when browsing website in Incognito mode in Google chrome.
Every thing works fine in normal mode.
Service worker code of my progressive web app is
var version = 'v2:';
var offlineFundamentals = [
'/',
'/offline.html'
];
var updateStaticCache = function () {
return caches.open(version + 'fundamentals').then(function (cache) {
return Promise.all(offlineFundamentals.map(function (value) {
var request = new Request(value);
var url = new URL(request.url);
if (url.origin != location.origin) {
request = new Request(value, {
mode: 'no-cors'
});
}
return fetch(request).then(function (response) {
var cachedCopy = response.clone();
return cache.put(request, cachedCopy);
});
}))
})
};
var clearOldCaches = function () {
return caches.keys().then(function (keys) {
return Promise.all(keys.filter(function (key) {
return key.indexOf(version) != 0;
}).map(function (key) {
return caches.delete(key);
}));
});
};
var limitCache = function (cache, maxItems) {
cache.keys().then(function (items) {
if (items.length > maxItems) {
cache.delete(items[0]);
}
})
};
var trimCache = function (cacheName, maxItems) {
caches.open(cacheName).then(function (cache) {
cache.keys().then(function (keys) {
if (keys.length > maxItems) {
cache.delete(keys[0]).then(trimCache(cacheName, maxItems));
}
});
});
};
var hasUrlCacheExcludeMatch = function (url) {
var cacheExcludeUrls = [
"https:\/\/example.com\/user\/login",
"https:\/\/example.com\/user\/register"
];
return cacheExcludeUrls.some(path => url.includes(path));
};
self.addEventListener("install", function (event) {
event.waitUntil(updateStaticCache().then(function () {
return self.skipWaiting();
}));
});
self.addEventListener("message", function (event) {
var data = event.data;
if (data.command == "trimCache") {
trimCache(version + "pages", 80);
trimCache(version + "images", 50);
trimCache(version + "assets", 50);
}
});
self.addEventListener("fetch", function (event) {
var fetchFromNetwork = function (response) {
var cacheCopy = response.clone();
if (event.request.headers.get('Accept').indexOf('text/html') != -1) {
if (!hasUrlCacheExcludeMatch(event.request.url)) {
caches.open(version + 'pages').then(function (cache) {
cache.put(event.request, cacheCopy).then(function () {
limitCache(cache, 80);
})
});
}
} else if (event.request.headers.get('Accept').indexOf('image') != -1) {
caches.open(version + 'images').then(function (cache) {
cache.put(event.request, cacheCopy).then(function () {
limitCache(cache, 50);
});
});
} else {
caches.open(version + 'assets').then(function add(cache) {
cache.put(event.request, cacheCopy).then(function () {
limitCache(cache, 50);
});
});
}
return response;
}
var fallback = function () {
if (event.request.headers.get('Accept').indexOf('text/html') != -1) {
return caches.match(event.request).then(function (response) {
return response || caches.match('/offline.html');
})
}
}
if (event.request.method != 'GET') {
return;
}
if (event.request.headers.get('Accept').indexOf('text/html') != -1) {
event.respondWith(fetch(event.request).then(fetchFromNetwork, fallback));
return;
}
event.respondWith(caches.match(event.request).then(function (cached) {
return cached || fetch(event.request).then(fetchFromNetwork, fallback);
}))
});
self.addEventListener("activate", function (event) {
event.waitUntil(clearOldCaches().then(function () {
return self.clients.claim();
}));
});
Browsing website in Normal mode in Google chrome works fine no error occures in console.
I am not good in service worker so I am unable to resolve this issue.
This is a bit unobvious.
Quota exceed error means that your out of available space, which is 6% of total space for Chrome.
For incognito mode all storage and workers api is working, but quota space is equals zero bytes and, thus, you can not write to it.