I've implemented a webworker inside a web-page that uses backbone. I want to start the webworker in my index.html file as soon as the web page begins to load.
Here's my index.html's javascript code:
var w;
startWorker();
function startWorker() {
alert("new worker");
if(typeof(Worker) !== "undefined") {
alert("new worker");
if(typeof(w) == "undefined") {
alert("new worker");
w = new Worker("js/models/worker_prefetch_starred.js");
}
w.onmessage = function(event) {
// Comunication WebWorker <-> Webapp
};
}
}
As you can se I'm only creating the worker and works fine.
Here's my worker_prefetch_starred.js webworker's javascript code:
define(["underscore", "backbone" ],
function ($, _) {
require('collections/folder_items').starred_items_fetched().then(function(starred_items) {
_.each(starred_items, function(item) {
var linked_item = item.get("item");
linked_item.isOnWebsql(linked_item);
});
});
});
When I execute the code it throws me : define is not defined
What should I do?
You should include importScripts('require.js'); in worker_prefetch_starred.js file.
Related
I'm trying to write Jasmine test code for a custom JS module(?) that cookies return visitors and redirects them to their cookie'd region.
The JS works fine, but it doesn't seem to be recognized by Jasmine / Protractor as those pages don't redirect as they should.
my spec.js file:
describe("cookies", function() {
var bridgepage = ('http://0.0.0.0:4567/');
var citypage = ('http://0.0.0.0:4567/nyc/');
// cookied visitors
it('should redirect to city pages for cookied visitors', function(){
browser.get(citypage);
browser.get(bridgepage)
browser.sleep(1000);
expect(browser.getCurrentUrl()).toEqual(citypage);
})
});
folder structure:
- source
-- javascripts
---- lib
-- all.js
-- cookies.js // file to test
- spec
-- javascripts
---- helpers
---- supoort
-- spec.js // specs
cookies.js file:
var cookies = (function() {
var utma = $.cookie("__utma");
var serviceArea = $.cookie('first_visit_service_area')
var isFirstVisit = function() {
if (utma == null) {
return false;
}
else {
var utmaArray = utma.split('.');
var firstVisitTime = utmaArray[2];
var currentVisitTime = utmaArray[4];
return (firstVisitTime == currentVisitTime);
}
}
[...]
// Set cookies according to (...)
// If the user has never visited the site, (...)
// If the user (...), (...)
if (utma == null) {
// user has apparently disabled cookies or blocked google analytics cookies
return;
}
if (window.location.pathname == '/' && serviceArea) {
redirectServiceArea();
}
if (isFirstVisit) {
setCookies();
}
}());
This my first attempt at writing JS tests, so any help would be much appreciated! :)
var tabs = require("sdk/tabs");
var iofile = require("sdk/io/file");
var widgets = require("sdk/widget");
var selection = require("sdk/selection");
function console_log(text) {
console.log(selection.text);
}
function print(text) {
console.log(text);
}
function dir_object(object_to_parse) {
var name = '';
for (name in object_to_parse) {
print(name);
}
}
function write_text(filename, text) {
var fh = iofile.open(filename, 'w');
var content = fh.read();
dir_object(fh);
selected_text = text + "\n";
fh.write(selected_text);
fh.flush();
fh.close()
}
function select_text_handler() {
write_text('/tmp/foo', selection.text);
}
var widget = widgets.Widget({
id: "scribus-link",
label: "Scribus website",
contentURL: "http://www.mozilla.org/favicon.ico",
onClick: function() {
}
});
selection.on('select', function () { select_text_handler(); });
'open' the file in 'w' and that truncates my existing file! How do i open in 'append' mode and then 'seek'?? https://addons.mozilla.org/en-US/developers/docs/sdk/latest/modules/sdk/io/file.htm
The file module of the SDK is pretty limited. When opening a file for writing it will always be truncated (code). Also, it is uses entirely synchronous I/O on the main thread, which isn't really a good thing to do, as it will block the entire UI during the I/O.
You should probably use another mechanism via the chrome module. See OS.File and/or the MDN File I/O snippets.
I have a array where i have specified the files i need to load in javascript before calling specific script. Lets call those particular lines of code as myscript.
I did as follows
var fileNamesArray = new Array();
fileNamesArray.push("abc.js");
fileNamesArray.push("pqr.js");
fileNamesArray.push("xyz.js");
fileNamesArray.push("klm.js");
var totalFiles = jQuery(fileNamesArray).length;
var tempCount = 0;
jQuery.each(fileNamesArray, function(key, value) {
jQuery.getScript(value, function() {
tempCount++;
});
});
to check whether all files are being loaded or not, i done following thing but doesn't seems to be effective
var refreshIntervalId = setInterval(function() {
if (tempCount == totalFiles) {
clearInterval(refreshIntervalId);
return;
}
}, 10);
i have implemented these in object oriented javascript as follows
function Loader() {
this.jQuery = null;
// check for specifically jQuery 1.8.2+, if not, load it
if (jQuery == undefined) {
jQuery.getScript(
"/Common/javascript/jquery/map/javascript/jquery-1.8.2.js",
function() {
this.jQuery = jQuery.noConflict();
});
} else {
var jQueryVersion = $.fn.jquery;
jQueryVersion = parseInt(jQueryVersion.split('.').join(""));
if (182 > jQueryVersion) {
jQuery.getScript(
"/Common/javascript/jquery/map/javascript/jquery-1.8.2.js",
function() {
this.jQuery = jQuery.noConflict();
});
}
}
}
Loader.prototype.LoadAllFile = function() {
//here i am loading all files
}
Loader.prototype.bindMap = function(options) {
this.LoadAllFile();
//execute the script after loading the files... which we called as myscript
}
i am loading more than 12-14 js files via ajax.
if you observe Loader.prototype.bindMap, i am loading all the files first and then executing the script.
But it seems that myscript the script start executing before all files being loaded.
what are the better ways to execute the script only after all js files are loaded.
Take a look at jQuery's .load() http://api.jquery.com/load-event/
$('script').load(function () { });
Based on the documentation on Jquery.getScript , it is a shorthand for Jquery.ajax. By default this in async call. You might want to change it to do a synchronous call.
To set this property, you can refer to this
So instead of doing a setInterval, you can just loop in your array and do a Jquery.getScript.
I am trying to implement an HTML5 WebWorker and I am using rails 3. I have this in my js code:
//When body(DOM) is ready
$(function() {
....
..
//test html5 webworkers
$('#test_html5_workers').click(function() {
var worker=new Worker('play.js');
worker.addEventListener('message', function(e) {
console.log('Worker said: ', e.data);
}, false);
worker.postMessage('Hello World'); // Send data to our worker.
});
..
....
)};
and in another file I have this (in play.js)
self.addEventListener('message', function(e) {
self.postMessage(e.data);
}, false);
I am currently getting this error:
Script file not found: play.js
I have tried other file path names with no luck.
Any ideas why I am getting this since both files are in the same directory, assets/javascripts?
I am using Firefox 17.0.1
The javascript file (play.js) should go in the public folder, or at least that's what I did to get it working.
This works on mine.
(function() {
//test html5 webworkers
$('#test').on('click', function(){
if(window.Worker){
var worker = new Worker('test.js');
worker.onmessage = function(e){
alert('worker said: ' + e.data);
}
worker.postMessage('start');
}
});
})();
//test.js
self.onmessage = function(e){
if(e.data === 'start'){
self.postMessage('booyeah');
}
}
Referring to this question: Add-on Builder: ContentScript and back to Addon code?
Here is my addon code:
var widget = widgets.Widget({
id: "addon",
contentURL: data.url("icon.png"),
onClick: function() {
var workers = [];
for each (var tab in windows.activeWindow.tabs) {
var worker = tab.attach({contentScriptFile: [data.url("jquery.js"), data.url("myScript.js")]});
workers.push(worker);
}
}
});
And here is myScript.js:
var first = $(".avatar:first");
if (first.length !== 0) {
var url = first.attr("href");
self.port.emit('got-url', {url: url});
}
Now that I have multiple workers where do I put
worker.port.on('got-url', function(data) {
worker.tab.url = data.url;
});
Since in the other question I only had one worker but now I have an array of workers.
The code would be:
// main.js:
var data = require("self").data;
var windows = require("windows").browserWindows;
var widget = require("widget").Widget({
id: "addon",
label: "Some label",
contentURL: data.url("favicon.png"),
onClick: function() {
//var workers = [];
for each (var tab in windows.activeWindow.tabs) {
var worker = tab.attach({
contentScriptFile: [data.url("jquery.js"),
data.url("inject.js")]
});
worker.port.on('got-url', function(data) {
console.log(data.url);
// worker.tab.url = data.url;
});
worker.port.emit('init', true);
console.log("got here");
//workers.push(worker);
}
}
});
// inject.js
$(function() {
self.port.on('init', function() {
console.log('in init');
var first = $(".avatar:first");
if (first.length !== 0) {
var url = first.attr("href");
console.log('injected!');
self.port.emit('got-url', {url: url});
}
});
});
Edit: sorry, should have actually run the code, we had a timing issue there where the content script was injected before the worker listener was set up, so the listener was not yet created when the 'got-url' event was emitted. I work around this by deferring any action in the content script until the 'init' event is emitted into the content script.
Here's a working example on builder:
https://builder.addons.mozilla.org/addon/1045470/latest/
The remaining issue with this example is that there is no way to tell if a tab has been injected by our add-on, so we will 'leak' or use more memory every time the widget is clicked. A better approach might be to inject the content script using a page-mod when it is loaded, and only emit the 'init' event in the widget's onclick handler.