Load JS script in the app running in local context - javascript

I have HTML/JS based UWP application. The app is running in local context, so my "Start page" in package manifest contains: index.html.
index.html contains following line:
<script src="ms-appdata:///temp/myScript.js"></script>
So myScript is placed in temporary (TempState) folder. I am aware that files in the temp folder can be deleted by system anytime.
When I launch the app I can see following error:
CSP14312: Resource violated directive 'script-src ms-appx: 'unsafe-eval' blob:' in Host Defined Policy: ms-appdata:///temp/myScript.js. Resource will be blocked.
I know that when I switch to web context by using ms-appx-web, it will work, however, is there any other way to load any JS script in the app running in local context?
UPDATE:
I just forgot to point out that the script is provided by somebody else and cannot be included in the app package.

This is a CSP error, it's not quite relevant to the web/local context. You need to configure your CSP in <meta/> tag on the index.html. Please see the Content Security Policy (CSP)
for more details.

Related

How do I write (flutter web) code so JavaScript files will run on my local machine?

I built a simple flutter web app. It works fine on github.io and also on the localhost server:
$ flutter run -d chrome
If I create a release build:
$ flutter build web
turning the app into (basically) a JavaScript file (main.dart.js), why can't I just run the app by loading the created index.html file?
The JavaScript debugger in my browser tells me this code:
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('flutter_service_worker.js');
});
}
</script>
produces the error:
Uncaught (in promise) TypeError: ServiceWorkerContainer.register: Script URL's scheme is not 'http' or 'https'
I'm not sure what this means or how to fix it. I know it's not as simple as just adding http in front of flutter_service_worker.js.
I believe the issue is that you are opening the index.html file locally via the file protocol. According to this SO answer, service workers need to be opened through an http or https protocol. That's why the index.html file is working on your localserver and github.io but not when you just open it via chrome or another browser.

Embedding React app as a widget with Javascript is failing with different messages on Firefox and Chrome

Following the steps on this site I'm able to embed a react app as a widget at another site with iframe:
<html>
<iframe src="http://localhost:3000"><iframe>
</html>
Embedding with Javascript (the second method) is failing with the following error message on Firefox:
The script from “http://localhost:3000/static/js/main.dbfc58d6.chunk.js” was loaded even though its MIME type (“text/html”) is not a valid JavaScript MIME type.
SyntaxError: expected expression, got '<'
Following is my code to embed the react app:
<html lang="en">
<body><noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script type="text/javascript" src="http://localhost:3000/static/js/main.dbfc58d6.chunk.js"></script>
</body>
</html>
I can confirm that the js source I specified is correct and running:
On Chrome, the warning message is displayed as below:
index.html:1 A cookie associated with a cross-site resource at http://localhost/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.
index.html:10 Cross-Origin Read Blocking (CORB) blocked cross-origin response http://localhost:3000/static/js/main.dbfc58d6.chunk.js with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.
Seeking guidance to solve this. Thank you for reading.
Update:
Referring to #Thai's answer, I'm specifying my source file as the one generated by the react build operation. How can I specify the right js file to solve my issue?
I can confirm that the js source I specified is correct and running
Thanks for posting that screenshot, because it is crucial to figuring out what the problem is. Contrary to what you said, the JS source is not correct. Your JavaScript source is just a text file, and it cannot run on its own inside a browser.
This means that when you view the JavaScript source file, you should see the source code, and not a working application.
However in your screenshot it shows the actual application and not the JavaScript source.
What you're actually getting is an HTML page. Your development server probably serves this page when a file you requested couldn’t be found. So it serves the index page as a fallback.
Next time, when confirming if something is correct, may I suggest that you try intentionally making it incorrect, and then see if the result differs?
Figured it out with assistance - the issue was due to the way I was creating the build.
We can't use the default build tool that comes with CRA. Use rescripts/cli instead.
Install #rescripts/cli as a dev dependency:
npm install #rescripts/cli --save-dev
Update package.json "scripts" to run with 'rescripts':
"scripts": {
"start": "rescripts start",
"build": "rescripts build",
"test": "rescripts test",
"eject": "rescripts eject"
},
Build your app with
npm run buiild
Embed the app with:
<script src="https://localhost:3000/static/js/bundle.js"></script>

Ruby on Rails & service worker

I'm trying to use a service worker in my Ruby on Rails application.
I need to use some erb features in my app/javascripts/service-worker.js.erb file. The service worker registration script looks like this:
var registerServiceWorker = function() {
navigator.serviceWorker.register(
'<%= asset_path('service-worker.js') %>',
{ scope: '/assets/' }
)
.then(function() {
console.info('Service worker successfully registered');
})
.catch(function(error) {
console.warn('Cannot register sercie worker. Error = ', error);
});
}
This does not work; I never get promise here:
navigator.serviceWorker.ready.then
I also tried ./ and / scopes but I got this error:
DOMException: Failed to register a ServiceWorker: The path of the
provided scope ('/') is not under the max scope allowed ('/assets/').
Adjust the scope, move the Service Worker script, or use the
Service-Worker-Allowed HTTP header to allow the scope.
If I move my service-worker.js to the public folder, remove the .erb extension and change scope to ./, everything works great, but I have no template engine there.
Any suggestions?
There's now a gem, serviceworker-rails that will allow you to proxy requests for serviceworker scripts in the asset pipeline. Because of the way browsers register serviceworker scripts, it's best to avoid caching them.
Sprockets will fingerprint assets and Rails (or your webserver) typically serves the compiled files with aggressive caching headers from the /assets directory.
What we want is the ability to customize service worker paths and response headers and still get Sprockets preprocessing, i.e. CoffeeScript/ES2015 to JavaScript transpilation.
The serviceworker-rails gem inserts middleware to your Rails stack that will proxy a request for /serviceworker.js (for example) to the corresponding fingerprinted, compiled asset in production. In development, you get the auto-reloading behavior you would expect. You can set up multiple serviceworkers at different scopes as well.
https://github.com/rossta/serviceworker-rails
Because of the security purpose, you can't register ServiceWorker in higher scope than from where it was executed.
If you really need template engine, you may try to dynamically load JS file from file in your /public folder (How do I include a JavaScript file in another JavaScript file?). Currently Service-Worker-Allowed HTTP header is not implemented yet in Firefox (https://bugzilla.mozilla.org/show_bug.cgi?id=1130101)
I'm running into this problem now as well. Based on my research, I think the proper way for a Rails application to handle service workers is to serve the service worker javascript file normally using the Asset pipeline, scope the service worker using the scope option (like you have done), and then use the Service-Worker-Allowed HTTP header to explicitly allow the new scope.
Unfortunately, at the moment there are several barriers to implementing this method:
Rails 4 (apparently) does not allow adding HTTP headers to Assets it serves, other than the cache-control header. To work around this you could add a Rack plugin as detailed in this S.O. answer, or in production if you are using an Asset server such as Nginx, you can get around this by having Nginx add the HTTP header. Though this doesn't help during development.
Rails 5 does allow adding HTTP headers to Assets however, as detailed in this blog post.
Browser support for service workers and the Service-Worker-Allowed HTTP header is currently poor.
Just do it in the root directory. For example, I put a route
get 'service-worker(.format)', to: 'core#service_worker'
Then just put in your controller (core_controller.rb in my example)
def service_worker
end
Then create app/views/core/service_worker.js.erb and put your JS there (including any <%= stuff %>).
I recently wrote an article about how to do that entirely with Webpacker. Please find my guide to a Progressive Web App with Rails.
In short:
add the webpacker-pwa npm package with yarn add webpacker-pwa and edit environment.js with:
const { resolve } = require('path');
const { config, environment, Environment } = require('#rails/webpacker');
const WebpackerPwa = require('webpacker-pwa');
new WebpackerPwa(config, environment);
module.exports = environment;
This will allow you to use service workers. Please check the README of the project as well: https://github.com/coorasse/webpacker-pwa/tree/master/npm_package
Leave the service worker file in whatever directory imposed by your project structure and set the scope option to / and add the Service-Worker-Allowed HTTP header to the response of your service worker file.
In ASP.Net, I added the following to web.config file:
<location path="assets/serviceWorker.js">
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Service-Worker-Allowed" value="/" />
</customHeaders>
</httpProtocol>
</system.webServer>
</location>
And register the worker by:
navigator.serviceWorker.register('/assets/serviceWorker.js', { scope: '/' })
.then(function (registration)
{
console.log('Service worker registered successfully');
}).catch(function (e)
{
console.error('Error during service worker registration:', e);
});
Tested on Firefox and Chrome.
Refer to the examples in Service worker specification

MeteorJS App not working correctly after *.meteor.com deploy

I've recently finished up a project in meteor for a contest, and am having trouble deploying to *.meteor.com.
The deploy itself works, as you can see here, but neither my dynamic templates on the home page that should show posts appear/work, nor can you create an account, etc. I believe I may have an issue with my routing.
I believe this may be a routing issue. I'm using version 0.9.1. The source code can be found here.
Any thoughts? Running locally it works great, and deploying with the --debug features doesn't help. No errors are present in the console.
The problem may be coming from your links to external scripts in your head tag. These should instead be loaded through a package.
Visiting your site my console reads:
Failed to load resource: the server responded with a status of 403 (Forbidden)
http://use.typekit.net/c/765ffa/azo-sans-web:i4:i7:n4:n7:n9,proxima-nova:i4…a7a4dd7b8a278a2bbbafab3833d56270f9b83c60ccd331a8fd4b7d3712346dcd4c9f5ac346
That is coming from these scripts in your head tag:
<script type="text/javascript" src="//use.typekit.net/mkh6uio.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
See if loading them through a package corrects things.

Javascript error in rails app (locally run)

I am trying to move a development environment from production to my local machine (Ubuntu), and when I get the code up and running on my box, the site works in rails but I get this JS error:
Permission denied for http://ad.doubleclick.net to call method Location.toString on http://localhost:3000.
Line 0
Do you have any idea how to fix JS problems, or should I disable the ads in development?
This is most likely an error that you can ignore. Its probably contained to an iframe created by the advertisement module.
I'm pretty sure that error occurs on the production version too, unless the production version is actually hosted at ad.doubleclick.net, which I guess its not :)

Categories