Javascript SignalR Stop Refused to execute script - javascript

I'm getting this error when calling $.connection.hub.stop();
Refused to execute script from ... because its MIME type ('') is not executable, and strict MIME type checking is enabled.
SignalR Client: jquery.signalR-2.2.3.min.js
SignalR Server: All Nugets are up to date
Startup.cs
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var Configuration = new HubConfiguration
{
EnableJSONP = true,
EnableJavaScriptProxies = true,
EnableDetailedErrors = true
};
map.RunSignalR(Configuration);
});
Javascript
$.connection.hub.start({ jsonp: true }).done(function () { ... });
Any ideas about fix?

Related

ASP.NET Core 3.1 CORS configuration gone wrong

The application is configured to use HTTPS. We want to be able to make calls from the client to a printer on their local network that exposes a simple api that uses HTTP. So from our javascript code we do a POST with a "text/plain" payload to send commands to the printer. When we send this request we get the following error.
jquery-3.3.1.min.js:2 Mixed Content: The page at 'https://...' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://.../pstprnt'. This request has been blocked; the content must be served over HTTPS.
Is there a way to configure CORS in such a way that only this traffic from and to a printer can be done using HTTP while the rest of the application uses HTTPS, without specifying the target IN startup.cs ? ( this is because the printers should be able to be expanded at runtime, so basically just 'allow all orgins', so that its not restricted to the ones specified in Startup.cs)
I have tried multiple guides online, but I'm guessing there is something wrong with our Startup.cs file structure.
The request to the printer looks like this:
$.ajax({
type: "POST",
url: "http://<printer-ip>/pstprnt",
data: 'some ZPL',
contentType: 'text/plain'
}).done((res) => {
console.log("second success");
}).fail((e) => {
alert(e);
})
Here is a snippet our Startup file.
CONFIGURE SERVICES
public void ConfigureServices(IServiceCollection services)
{
// Add Cors
services.AddCors();
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
/* (Verification/password reset) email sender */
//services.AddTransient<IEmailSender, EmailSender>();
//services.Configure<AuthMessageSenderOptions>(Configuration);
Task.Run(() => {
var options = new DbContextOptionsBuilder<ApplicationDbContext>().UseSqlServer(Configuration.GetConnectionString("DefaultConnection")).Options;
using (var dbContext = new ApplicationDbContext(options)) {
var model = dbContext.AankoopProduct;
}
});
services.AddLocalization();
/*
I commented this out because I am using UseEndpoints, Am I doing this correctly?
services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization().AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
*/
services.AddIdentity<Gebruiker, IdentityRole>(options =>
{
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
options.SignIn.RequireConfirmedEmail = true;
}).AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.Configure<IdentityOptions>(options =>
{
// Password settings.
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = true;
options.Password.RequiredLength = 6;
options.Password.RequiredUniqueChars = 1;
});
services.AddControllersWithViews().AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
// .cshtml views & .razor components
services.AddRazorPages();
//SignalR for Websockets
services.AddSignalR();
// reload views after changing JS
#if DEBUG
var mvcBuilder = services.AddControllersWithViews();
mvcBuilder.AddRazorRuntimeCompilation();
#endif
services.ConfigureApplicationCookie(opts => opts.LoginPath = "/Account/Login");
/* Breadcrumbs */
services.AddBreadcrumbs(GetType().Assembly, options =>
{
options.TagName = "nav";
options.TagClasses = "";
options.OlClasses = "breadcrumb breadcrumb--transparent m-0";
options.LiClasses = "breadcrumb-item";
options.ActiveLiClasses = "breadcrumb-item active";
//options.SeparatorElement = "<li class=\"separator\">/</li>";
});
/* Repositories */
services.RegisterRepositories();
services.AddSession();
}
CONFIGURE
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IVerkoopProductXMLRepository rep)
{
//app.ApplicationServices.GetService<IInkomendeBestellingTrackerSingleton>();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
#region Auth
var supportedCultures = new[]
{
new CultureInfo("nl-BE")
};
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("nl-BE"),
// Formatting numbers, dates, etc.
SupportedCultures = supportedCultures,
// UI strings that we have localized.
SupportedUICultures = supportedCultures
});
var cultureInfo = new CultureInfo("nl-BE");
cultureInfo.NumberFormat.CurrencySymbol = "€";
cultureInfo.NumberFormat.NumberDecimalSeparator = ".";
CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("nl-BE");
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("nl-BE");
// To configure external authentication,
// see: http://go.microsoft.com/fwlink/?LinkID=532715
#endregion
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseStatusCodePages();
app.UseRouting();
app.UseSession();
// Enable Cors
app.UseCors();
/*
I commented this out because I am using UseEndpoints() , Am I doing this correctly?
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=UserSelection}/{id?}");
});
*/
app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Account}/{action=Login}/{id?}");
});
}
This doesn't relate to your ASP.NET CORS configuration, because you're making a request directly from the client (the browser) to the printer; CORS would come into play if you were making cross-domain requests to the ASP.NET API.
What you could do is make the request to the printer from the server, instead, assuming your network topology permits it. Make an AJAX request from your JS to a new endpoint on the server, which then makes a plain HTTP request to the printer.

How can I tell whether chrome.proxy.settings.set is correctly setting my proxies

In my Google Chrome Extension, my popup.js includes:
function setProxyToUse() {
var enable = {
mode: "fixed_servers",
rules: {
proxyForHttps: {host: localStorage["surveyHTTPS"]},
proxyForHttp: {host: localStorage["surveyHTTP"]}
}
};
var disable = {mode: "system"}
if (localStorage["proxyOn"] == true) {var config = enable} else {var config = disable}
chrome.proxy.settings.set({value: config, scope: 'regular'},function() {});
chrome.proxy.settings.get({}, function(config) {console.log(config.value.host);} );
}
The last line simply writes undefined to the console. How can I check which proxy host I'm using?
By default proxy value is a string "system" which doesn't have the property you're trying to display (.host).
If you want to read the value you've just set, do it in the callback of .set because chrome API is asynchronous:
chrome.proxy.settings.set({value: config, scope: 'regular'}, function() {
chrome.proxy.settings.get({}, function(config) {
console.log(config.value, config.value.host);
});
});

how to add a basic keen.io event with javascript

I am trying to set up a basic example that sends a custom keen.io event via js. At the moment I do not need any presentation, visualisation, etc.
Here is the example that I created from another one I found online. I attempted several variations, and all of them work in Google Chrome, but none of them works in Firefox (38.0 for Ubuntu canonical - 1.0).
if I add to the head the inline script (!function(a,b){a("Keen"...) as it is proposed in the manual, I do not get any errors in FF, but it seems that addEvent never gets called and it produces no response, "err" nor "res".
if I include the library from the CDN (d26b395fwzu5fz.cloudfront.net/3.2.4/keen.min.js), I get an error when the page is loaded:
ReferenceError: Keen is not defined
var keenClient = new Keen({
If I download the js file and serve it locally, after the button is clicked, I get the following error response:
Error: Request failed
err = new Error(is_err ? res.body.message : 'Unknown error occurred');
All of these attempts work from Chrome, but I need this to work from other browsers too.
I received a response from keen.io team. It turned out that Adblock Plus is interfering with the script. After I disabled it everything works in FF as in Chrome.
After some investigation in turned out that request to http://api.keen.io was blocked by "EasyPrivacy" filter of ABP with these filter rules: keen.io^$third-party,domain=~keen.github.io|~keen.io
So, sending a request to an "in-between" server (a proxy) seems to be the only solution that I can see.
We have a bit specific use case - a need to track a static site and also an available access to a rails api server, but the solution we ended up using may come useful to someone.
error.html
<html>
<head>
<title>Error</title>
<script src="/js/vendor/jquery-1.11.2.min.js"></script>
<script src="/js/notification.js"></script>
<script type="text/javascript">
$(document).on('ready', function () {
try {
$.get(document.URL).complete(function (xhr, textStatus) {
var code = xhr.status;
if (code == 200) {
var codeFromPath = window.location.pathname.split('/').reverse()[0].split('.')[0];
if (['400', '403', '404', '405', '414', '416', '500', '501', '502', '503', '504'].indexOf(codeFromPath) > -1) {
code = codeFromPath;
}
}
Notification.send(code);
});
}
catch (error) {
Notification.send('error.html', error);
}
});
</script>
</head>
<body>
There was an error. Site Administrators were notified.
</body>
</html>
notification.js
var Notification = (function () {
var endpoint = 'http://my-rails-server-com/notice';
function send(type, jsData) {
try {
if (jsData == undefined) {
jsData = {};
}
$.post(endpoint, clientData(type, jsData));
}
catch (error) {
}
}
// private
function clientData(type, jsData) {
return {
data: {
type: type,
jsErrorData: jsData,
innerHeight: window.innerHeight,
innerWidth: window.innerWidth,
pageXOffset: window.pageXOffset,
pageYOffset: window.pageYOffset,
status: status,
navigator: {
appCodeName: navigator.appCodeName,
appName: navigator.appName,
appVersion: navigator.appVersion,
cookieEnabled: navigator.cookieEnabled,
language: navigator.language,
onLine: navigator.onLine,
platform: navigator.platform,
product: navigator.product,
userAgent: navigator.userAgent
},
history: {
length: history.length
},
document: {
documentMode: document.documentMode,
documentURI: document.documentURI,
domain: document.domain,
referrer: document.referrer,
title: document.title,
URL: document.URL
},
screen: {
width: screen.width,
height: screen.height,
availWidth: screen.availWidth,
availHeight: screen.availHeight,
colorDepth: screen.colorDepth,
pixelDepth: screen.pixelDepth
},
location: {
hash: window.location.hash,
host: window.location.host,
hostname: window.location.hostname,
href: window.location.href,
origin: window.location.origin,
pathname: window.location.pathname,
port: window.location.port,
protocol: window.location.protocol,
search: window.location.search
}
}
}
}
return {
send: send
}
}());
example of sending notification manually from js code:
try {
// some code that may produce an error
}
catch (error) {
Notification.send('name of keen collection', error);
}
rails
# gemfile
gem 'keen'
#routes
resource :notice, only: :create
#controller
class NoticesController < ApplicationController
def create
# response to Keen.publish does not include an ID of the newly added notification, so we add an identifier
# that we can use later to easily track down the exact notification on keen
data = params['data'].merge('id' => Time.now.to_i)
Keen.publish(data['type'], data) unless dev?(data)
# we send part of the payload to a company chat, channel depends on wheter the origin of exception is in dev or production
ChatNotifier.notify(data, dev?(data)) unless data['type'] == '404'
render json: nil, status: :ok
end
private
def dev?(data)
%w(site local).include?(data['location']['origin'].split('.').last)
end
end

Refused to execute script from '*'

At https://rawgit.com/UserName/master/file.json (dummy URL) I am hosting a JSON file.
The exact JSON file being hosted it this:
[
{
"name":"Europe",
"id":1
},
{
"name":"USA",
"id":2
}
]
And when I try to obtain this via AngularJS:
return{
fetchData : function(remoteDataId){
var deferred = $q.defer();
var url = 'https://cdn.rawgit.com/Username/master/' + remoteDataId;
$http.get(url, { cache:true }).then
(
function(resp){
deferred.resolve(resp.data)
},
function(err){
deferred.reject();
}
)
return deferred.promise;
}
};
I get this error : Refused to execute script from 'https://rawgit.com/UserName/master/file.json?callback=angular.callbacks._3' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.
What is wrong here? According to JSLint my JSON is valid. Should I add anything to the .json file?
I changed $http.jsonp() to $http.get(). It works even though it is a cross origin request.

getUserMedia fails with TrackStartError when allowing accessing to microphone

I am using Chrome Version 35.0.1916.114 m
When I run my html page using IIS (e.g., localhost/test.html) and hit "Allow" to the http://localhost/ wants to use your microphone prompt, getUserMedia() fails with the following error:
NavigatorUserMediaError {constraintName: "", message: "", name: "TrackStartError"}
Code:
var constraints = {audio: true, video: false};
...
function successCallback(stream) {
...
}
function errorCallback(error){
console.log("navigator.getUserMedia error: ", error);
}
navigator.getUserMedia(constraints, successCallback, errorCallback);
What could be the cause of this error?
var mediaConstraints =
{
'mandatory' :
{
'OfferToReceiveAudio' : true,
'OfferToReceiveVideo' : false
}
};
declare this in your code before using constraints.

Categories

Resources