Work with the simple-prefs module and export the values to a script stored in the data folder - firefox-addon

I'm currently trying to add some preferences to a Firefox add-on. To do so, I'm playing with the new "simple-prefs" module. (Simple-Prefs on the Mozilla Blog)
The documentation is not very detailed and I face some problems understanding how I can retrieve the value attached to an option and export it to a JS script present in my data folder.
Let's say that I have only one optional setting in my addon, a boolean one, then my packages.json will look like this:
{
"name": "test",
...
"preferences": [{
"type": "bool",
"name": "option1",
"value": true,
"title": "Desc Option 1"
}]
}
Here is my main.js file [UPDATED]:
var pageMod = require("page-mod");
const data = require("self").data;
const prefSet = require("simple-prefs"); //Simple-prefs module
var option1 = prefSet.prefs.option1; //get the value for option1
function onPrefChange(prefName) { //Listen for changes
var prefName = prefSet.prefs[prefName];
}
prefSet.on("option1", onPrefChange);
exports.main = function() {
pageMod.PageMod({
include: ["https://mail.google.com/*","http://mail.google.com/*"],
contentScriptWhen: 'ready',
contentScriptFile: [data.url("jquery.js"),data.url("script.js")],
onAttach: function(worker)
{
worker.postMessage( option1 );
}
});
}
How can I retrieve the value attached to "option1" and export it in order to call it in my "script.js" file?

As usually, content scripts don't have access to the API - they can only receive messages from your extension's scripts. Here you would do:
pageMod.PageMod({
include: ["https://mail.google.com/*","http://mail.google.com/*"],
contentScriptWhen: 'ready',
contentScriptFile: [data.url("jquery.js"),data.url("script.js")],
onAttach: function(worker)
{
worker.postMessage(backtop);
}
});
And in the content script you would have the following code:
self.on("message", function(data)
{
alert("Received option value: " + data);
});
This message arrives asynchronously meaning that your content script won't know the option value initially - but that's how content scripts work.

Related

Typescript equivalent of inline JavaScript

This may be self-evident but I'm not finding any example that informs what I'm trying to do (maybe I'm just doing it wrong). I'm adding Vue to an existing ASP.NET Core MVC application and adding the JavaScript statements directly to the page works but when I try to migrate to a TypeScript file nothing happens.
The JavaScript is:
new Vue({
el: "#productPage",
data: {
isLoading: true
},
methods: {
},
mounted () {
console.log("mounted()");
this.isLoading = false;
}
});
This works as expected. Migrating the code to a TypeScript file productPage.ts:
import Vue from 'vue';
new Vue({
el: "#productPage",
data: {
isLoading: true
},
methods: {
},
mounted () {
console.log("mounted()");
this.isLoading = false;
}
});
Which generates:
(function (factory) {
if (typeof module === "object" && typeof module.exports === "object") {
var v = factory(require, exports);
if (v !== undefined) module.exports = v;
}
else if (typeof define === "function" && define.amd) {
define(["require", "exports", "vue"], factory);
}
})(function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var vue_1 = require("vue");
var HonestyBox;
(function (HonestyBox) {
new vue_1.default({
el: "#productPage",
data: {
isLoading: true
},
methods: {},
mounted: function () {
console.log("Mounted !!!!");
this.isLoading = false;
}
});
})(HonestyBox || (HonestyBox = {}));
});
//# sourceMappingURL=productPage.js.map
And including the generated javascript file productPage.js:
<script src="~/js/productPage.js"></script>
This does nothing. Stepping through the debugger neither of the conditions in function(factory) are satisfied. The console tells me You are running Vue in development mode. but the included JavaScript fails to run. The tsconfig.json used to generate the JavaScript file:
{
"compileOnSave": true,
"compilerOptions": {
"module": "umd",
"moduleResolution": "node",
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": true,
"sourceMap": true,
"target": "es5",
"outDir": "wwwroot/js"
},
"include": [
"Typescript/**/*"
],
"exclude": [
"node_modules",
"wwwroot"
]
}
Using "module": "commonjs" results in ReferenceError: exports is not defined. I was hoping to avoid having to use Browserify or Webpack.
If I understand you correctly you add Vue in a separate script tag before your productPage.js.
This means that you can't import Vue in your TypeScript file, but you need to declare Vue so the module just assumes that Vue has been loaded already (outside of your TS module).
declare const Vue; // this replaces your Vue import statement
If you want to add a bundler later on, you need to remove your script tag which loads Vue and only go the modular approach:
Vue needs to be imported with an import statement so the bundler knows that he has to include all of Vue.
You will then have one single JS file (or if your bundler splits it: multiple JS files).

How to use port.on() and port.emit() with each other

I am trying to use a page-worker and a pageMod together using port.on() and port.emit(), but the signals from define.js do not have any effect on the pageMod's port.on()... Is this the proper way to use port.on() and port.emit() or is chaining the two together this way not allowed?
index.js:
pageMod.PageMod({
include: "*",
contentScriptWhen: "ready",
contentScriptFile: [
data.url("jquery.js"),
data.url("jquery-ui.min.js"),
data.url("define.js")
],
onAttach: function(worker){
worker.port.on("getWord", function(word) {
console.log(word);
worker.port.emit("newWord", word);
});
worker.port.on("updatedWord", function(URL){
console.log(URL);
});
}
});
dictionaryRef.Page({
contentScriptWhen: "ready",
contentScriptFile: [
data.url("jquery.js"),
data.url("jquery-ui.min.js"),
data.url("define.js"),
],
contentURL: "http://www.dictionary.com/browse/",
onAttach: function(worker){
worker.port.on("newWord", function(word) {
console.log(word);
self.contentURL = "http://www.dictionary.com/browse/" + word;
worker.port.emit("updatedWord", self.contentURL);
});
}
});
define.js:
$(window).dblclick(function() {
var selected = getSelected();
if (selected!="") {
calldictionary(selected);
var completedURL = "http://www.dictionary.com/browse/" + selected;
pageMod.port.emit("getWord", selected);
$('#define').dialog("open");
dictionaryRef.contentURL = completedURL;
}
});
function getSelected() {
if (window.getSelection) {
return window.getSelection().toString();
} else if (document.selection) {
return document.selection.createRange().text;
}
return '';
}
Basically, getSelected() will capture a highlighted word and then the "dblclick" binding should send a signal via port.emit() that the pageMod should receive, then pass onto a page-worker to change its URL, which would allow me to access the DOM and scrape the dictionary definition so that it can be displayed in the main window in a popup. At the moment, none of the port.emit() statements work.

Click event in select2 tag with a link

I am using select2 in tag mode. My item text is a link, e.g.:
<a href='url'>tag1</a>.
select2 seems to be swallowing the click event on the tag (selected choice) so I cannot navigate to the link.
Any ideas on how to get the link to work?
Select2 disables click events by default and for the moment, you must use a workaround to achieve the desired results. Here's an example of how I accomplished this, thanks to the resources below. This won't work if you don't re-instantiate the variable with the return value of .data('select2')
First, add a class to your links:
hello
Then you have to listen to the onSelect event of Select2
var search = $("#searchBox");
search.select2({
placeholder: "Search...",
allowClear: true,
minimumInputLength: 3,
maximumSelectionSize: 1,
escapeMarkup: function(m) { return m; },
ajax: { blah blah blah },
formatResult: window.App.formatFunction
});
search= search.data('select2');
search.onSelect = (function(fn) {
return function(data, options) {
var target;
if (options != null) {
target = $(options.target);
}
if (target && target.hasClass('detail-link')) {
window.location = target.attr('href');
} else {
return fn.apply(this, arguments);
}
}
})(search.onSelect);
This question/answer/JFiddle helped me out but its important to note the .data('select2') line
EDIT: forgot the resource -- https://stackoverflow.com/a/15637696
I use select2-selecting event:
var $q = $('#select2input');
$q.select2({
// your settings
});
$q.on('select2-selecting', function(e){
window.location = e.choice.url;
});
My AJAX payload looks like this:
{
"items":[
{
"id": "1",
"text": "Foo",
"url": "/foo"
},
{
"id": "8",
"text": "Bar",
"url": "/bar"
}
]
}

How to check files already uploaded in Uploadify JQ plugin?

I have to prevent users adding files which is already added in the server in 'uploadify' jquery plugin.
There is a grid which shows files which are already added, so I'm planning to get the files name collection from the grid and check it when on select function for preventing to add the already uploaded files.
Is there any better or easy way to do this?
Please help in finishing the code.
Will the above logic work ?
var uploadQueue = new Array();
jQuery().ready(function ($) {
debugger;
$.ajax({
type: "POST",
async: false,
url: ROOT + "Documents/DocumentAJAXController",
data: { "ID": $('[id="ID"]').val() },
success: function (result) {
}
});
$("#SubmitButton1").hide();
$("#fileuploader").fileUpload({
'uploader': "#Url.Content("~/Scripts/FileUpload/uploader.swf")",
'cancelImg': "#Url.Content("~/Content/Images/clearBtn.png")",
'buttonText': 'Browse Files',
//'buttonImg' : "#Url.Content("~/Content/Images/attachDoc.png")",
'script': "#Url.Content("~/Documents/Upload/")",
'folder': "#Url.Content("~/Documents/")",
//'fileDesc': 'Documents Files',
'fileExt': '*.pdf;*.doc;*.ppt;*.xls',
'multi': true,
'auto': false,
onError: function (a, b, c, d) {
},
'onSelect': function (event, queueID, fileObj) {
// uploadQueue.push(queueID);
},
'onAllComplete': function(event,data){
alert("Uploaded successfully");
$('.popupClose').click();
}
});
This functionality is built into the latest version of uploadify.
Uploadify provides for a checkScript handler in the settings that you pass to uploadify.
If you point this at an appropriate server script it will not allow files that already exist.
A sample script called check-exists.php is provided in the uploadify zip.

Jquery Autocomplete

iam using jquery autocomplete in asp.net project. it's not working. do you have any idea. the code is given below.
<script type="text/javascript">
$(function () {
$('#clientabbrev').val("");
$("#clientstate").autocomplete({
source: "clientstates.aspx",
select: function (event, ui) {
$('#clientstateid').val(ui.item.clientid);
$('#clientstateabbrev').val(ui.item.clientabbrev);
}
});
$("#clientstate_abbrev").autocomplete({
source: "clientstatesabbrev.aspx",
minLength: 2
});
});
</script>
problem is states.aspx returning the data but it is not showing in the jquery autocomplete control.
Your server needs to return a JSON serialized array of objects with properties id, label, and value. E.g. :
[ { "id": "1", "label": "Mike Smith", "value": "Mike Smith" }, { "id": "2", "label": "Bruce Wayne", "value": "Bruce Wayne" }]
Can you confirm with firebug or Fiddler that your server is returning the correct response?
If you're having trouble serializing your data in C#, you can try using JavaScriptSerializer like this:
var result = from u in users
select new {
id = u.Id,
value = u.Name,
label = u.Name
};
JavaScriptSerialier serializer = new JavaScriptSerializer();
var json = serializer.Serialize(result);
// now return json in your response

Resources