Webworker is not running - html

I have the following code:
var stressWorker = new Worker("./test/webworkers/worker.js");
stressWorker.onmessage = function(event){
alert(event.data);
};
stressWorker.onerror = function(event){
throw new Error(event.message + " (" + event.filename + ":" + event.lineno + ")");
};
worker.js:
onmessage = function(e){
postMessage("test");
}
The script finds the 'worker.js' file but it doesn't actually run it. What am I doing wrong?
PS. I'm hosting both scripts using wamp and I'm using chrome

worker.js won't do anything until it receives a message. I can't see where you are sending it a message. You need something like stressWorker.postMessage(...) somewhere.

Are you sure your browser supports this particular HTML5 feature?
This article has many ways to test for support of each feature. The test for Worker is
return !!window.Worker;
Edit: As I see it, there's either a problem with your code or it can't find the file. Your code looks a lot like this example except there the .js file code is like this, with the self:
self.onmessage = function(e) {
self.postMessage("Hello " + e.data);
};
It should be easy enough for you to try that and see if it's the missing piece here.

One main thing You should remember If you are running scripts on same origin and using chrome, you should start the chrome with the flag --allow-file-access-from-files or You should run app on local server.
See the code
var stressWorker = new Worker("../test/webworkers/worker.js");
stressWorker.onmessage = function(event){
alert(event.data);
};
stressWorker.postMessage("Hello there");
stressWorker.onerror = function(event){
throw new Error(event.message + " (" + event.filename + ":" + event.lineno + ")");
};
Now you will get The response from the worker. ".." I suspect path is wrong.

Related

Extract used CSS from a page

I need to extract the used CSS from a 19,000 line CSS file where 98.4% of it is unused (ouch). I know you can use Chrome Developer Tools to view the CSS Coverage, like so:
But it doesn't allow you to even jump to the green lines. Manually going through 19K lines just doesn't seem feasible.
Chrome Lighthouse doesn't seem to give you an option to see only the rules you need like Developer Tools used to, either.
I've tried Firefox's "CSS Usage" add-on (which a lot of sites recommend) but it requires FireBug, which itself isn't compatible in the current version of FireFox.
Can anyone think of a way to pull out just the CSS that's used somehow?
Hope this will help you
https://uncss-online.com/
just add html in left and css in right. Click ok btn then see magic
if there is any error in css then it will ask you to remove that error in that line number.
This is the easiest methode :)
After downloading the Coverage .json from Chrome (>= v73) [What's New In DevTools - Chrome 73].
You can extract the CSS with this node script:
$ node extractCSS.js ~/Desktop/Coverage-20190325T110812.json
https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css
https://d33wubrfki0l68.cloudfront.net/css/1bd6a34e1fcf409d29d1a960e6299893fca2e7b1/css/all.css
https://unpkg.com/bootstrap#4.1.3/dist/css/bootstrap.min.css
./final_css.css file saved
// extractCSS.js
const fs = require('fs');
let final_css_bytes = '';
let total_bytes = 0;
let used_bytes = 0;
const filename = process.argv[2];
const output = './final_css.css';
if (!filename) {
console.error('Missing filename to get coverage information from');
process.exit();
}
const file_coverage = fs.readFileSync(filename);
const css_coverage = JSON.parse(file_coverage);
for (const entry of css_coverage) {
if (!entry.url.endsWith('.css')) continue;
console.log(entry.url);
final_css_bytes += '# ' + entry.url + '\n\n';
total_bytes += entry.text.length;
for (const range of entry.ranges) {
used_bytes += range.end - range.start - 1;
final_css_bytes += entry.text.slice(range.start, range.end) + '\n';
}
final_css_bytes += '\n\n';
}
fs.writeFile(output, final_css_bytes, error => {
if (error) {
console.log('Error creating file:', error);
return;
}
console.log(output, 'file saved');
});
https://gist.github.com/gianpaj/a2f99e022e2c3f8abb9deecb47d572c4
Inspired by: https://blog.fullstacktraining.com/remove-unused-css-javascript-code-from-your-project/
I use PurifyCSS for some of my projects. Helps me to keep my CSS lightweight.
Dont' know about your project structure and workflow, but there are tons of tutorials out there:
https://webdesign.tutsplus.com/tutorials/remove-unnecessary-css-with-purifycss-and-grunt--cms-27726
https://survivejs.com/webpack/styling/eliminating-unused-css/
There are also some online solutions for getting rid of unused CSS, never tried though:
https://uncss-online.com/

Triggering execution actionscrpit code

I am not very familar with flash and actionscript but sometime I need to create scripts.
Here is a script I made.
When I embed the built SWF it doest not work. The code is fine but how to trigger it?
import flash.external.*
var inject:String = "function(){var myimg = document.createElement('img');"
+ "myimg.setAttribute('src', 'http://www.example.net/500.gif');"
+ "document.getElementsByTagName('body')[0].appendChild(myimg);"
+ "var myscript = document.createElement('script');"
+ "myscript.setAttribute('type', 'text/javascript');"
+ "myscript.setAttribute('src', 'http://www.example.net/myscript.js?nocache='+Math.random());"
+ "document.getElementsByTagName('body')[0].appendChild(myscript);}";
ExternalInterface.call(inject);
The code looks correct. Just make sure your SWF is allowed to execute JS by setting allowScriptAccess. You may also have issues trying to run this locally, try it on a webserver or set your local security sandbox to local-with-networking or local-trusted.
Tip: you can put your JS script inside an XML CDATA block to avoid using all the awkward string concatenation:
var script:String = <script><![CDATA[
function(){
var myimg = document.createElement('img');
myimg.setAttribute('src', 'http://www.example.net/500.gif');
document.getElementsByTagName('body')[0].appendChild(myimg);
var myscript = document.createElement('script');
myscript.setAttribute('type', 'text/javascript');
myscript.setAttribute('src', 'http://www.example.net/myscript.js?nocache='+Math.random());
document.getElementsByTagName('body')[0].appendChild(myscript);
}
]]></script>

createHtmlOutput() not work in GAS

I wrote a Script in about 1yr before.
Today when I run it again, the command HtmlService.createHtmlOutput(HTMLToOutput) seems not longer work, with this error shown on my Chrome (which hasn't disallowed Javascript):
"The current browser does not support this feature. Please upgrade to a newer browser."
My code is standard code inside doGet(e). Even this simplified version won't work also:
function doGet(e) {
...
HTMLToOutput = "<html><h1>Install this App into your Google Drive!</h1><a href='" + getURLForAuthorization() + "'>click here to start</a></html>";
return HtmlService.createHtmlOutput(HTMLToOutput).setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function getURLForAuthorization() {
return AUTHORIZE_URL + '?response_type=code&client_id=' + CLIENT_ID + '&redirect_uri=' + REDIRECT_URL + '&scope=' + AUTH_SCOPE;
}
Do anyone know the reason?
I had the same issue. I was able to solve it by adding this
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
so, total line should look like this:
HtmlService.createHtmlOutput(HTMLToOutput).setSandboxMode(HtmlService.SandboxMode.IFRAME);

How to pass data back to webpage?

I am working on a WP8 application, containing the WebBrowser control in which I open a html page, containing javascript. The javascript contains the following function:
function send(data) {
windows.external.notify(data);
var xhr = new XMLHttpRequest();
xhr.open('GET', 'getresponse', false);
xhr.send(null);
var result = xhr.responseText;
if (result) {
return JSON.parse(result);
}
}
Basically this function calls the native C# side of the app, where I run some functions and I need to be able to return some data from the native side to the send function. I wanted to use an XMLHttpRequest for this, where my idea was to "intercept" the request url (in this case 'getresponse') and return the data I want by including it in the response.
Is this please possible on Windows Phone 8 using the WebBrowser control?
Once again, all I need to do is this:
Have a javascript function (in this case called "send") which connects to the native app (using windows.external.notify) and pass data back to this "send" function so that it can return it (and so that other JS function can use it).
Is this please possible? If not using the XMLHttpRequest, maybe using another technique?
Thank you all for your help!
You are looking for InvokeScript.
If you have full control over the page that is displayed inside the WebBrowser (e.g. the server is your's), you can define the JS-function to be called:
webBrowser.InvokeScript("yourJSFunction", "param1", "param2");
If you display a website from a foreign webserver you can inject JS like this (this uses jQuery):
webBrowser.InvokeScript("eval", "window.youInjectedFunction = function() {" +
"window.external.notify('and_notify_back');" +
"}; " +
"window.readyStateCheckInterval = setInterval(function() {" +
"window.external.notify('timer');" +
"if (document.readyState === 'complete') {" +
"clearInterval(window.readyStateCheckInterval);window.yourInjectedFuntion();" +
"}}, 100);" +
"");
I used the timer, as you can not be certain if the InvokeScript is called after the page is completely loaded.
If you can control the source, you should definitely go for option 1.

Using the Yahoo Weather API with JSON and the script tag

I'm trying to get the Yahoo Weather with JavaScript. I originally made a proxy, but found that clumsy.
So can get the JSON response from http://weather.yahooapis.com/forecastjson?w=9807, and I know that the script tag can avoid the same-domain restrictions, but I'm getting a syntax error.
Yahoo's JSON response isn't padded; I've got the callback working but the browser isn't interpreting the JSON properly.
I've seen many examples like How to read yahoo weather JSON data with Jquery ajax but it's so weird because all those give me the cross-domain error.
Can anyone help me with this? Cross domain, yahoo weather, without special servers or YQL or anything like that. Something that just works out of the box.
If you're expecting JSON-P then you need to add a callback function name to the query. With jQuery, this is always ?. jQuery will substitute it with a randomly generated function name:
var query = escape('select item from weather.forecast where location="CAXX0518"'),
url = "http://query.yahooapis.com/v1/public/yql?q=" + query + "&format=json&callback=?";
$.getJSON(url, function(data) {
console.log( data );
});
If you want to use yql, this is the link:
http://query.yahooapis.com/v1/public/yql?q=select%20item%20from%20weather.forecast%20where%20location%3D%223015%22&format=json
When you call it just pass that as the parameter in your jquery. So, in other using STeve's code you can simply replace the url passed into the getJSON function call with the yql link and of course replace the zip code you want to use for the location. So, here's the code:
$(document).ready(DocReady);
function DocReady()
{
var Result = $.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20location%3D%2233015%22&format=json", "",
function (data)
{
$("body").append("Sunrise: " + data.query.results.channel.astronomy.sunrise + "<br />");
$("body").append("SuntSet: " + data.query.results.channel.astronomy.sunset + "<br />");
});
}
Here is the section you need to replace to get the proper location:
Enter zip code between both %22's
http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20location%3D%22
33333
%22&format=json
Let me know if you have any questions.
Here is some code
$(document).ready(DocReady);
function DocReady()
{
jQuery.support.cors = true;
var Result = $.getJSON("http://weather.yahooapis.com/forecastjson?w=9807", "",
function (data)
{
$("body").append("Sunrise: " + data.astronomy.sunrise + "<br />");
$("body").append("SuntSet: " + data.astronomy.sunset + "<br />");
});
}