How to inject script locally in firefox add-on - firefox-addon

I have published a add-on in mozilla add-on website, it got rejected because of remote scripts.
lib/Main.js:
var data = require("sdk/self").data;
var pageMod = require("sdk/page-mod");
var _workers = [];
pageMod.PageMod({
include: "some url",
contentScriptWhen: "ready",
contentScriptFile: data.url("./inject.js"),
contentStyleFile: data.url("style.css"),
attachTo: 'top'
});
data/inject.js:
var script = document.createElement('script');
script.type = "text/javascript";
script1.src = "https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js";
document.body.appendChild(script);
var script2 = document.createElement('script');
script2.type = "text/javascript";
script2.src = "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js";
document.body.appendChild(script2);
var script3 = document.createElement('script');
script3.type = "text/javascript";
script3.src = "resource://addon-id/addon-name/data/popup.js";
document.body.appendChild(script3);
Please help me to insert these scripts to the web content or insert these scripts locally from my addon.
And what is remote script?

All the code you use should be reviewable and immutable, google.com being controlled by a suspicious company, is not trustworthy, and can replace jquery.min.js with password/credit card collector, without Mozilla noticing.
To avoid suspicion, copy files required to your plugin's directory, and use them as:
var data = require("sdk/self").data;
var pageMod = require("sdk/page-mod");
pageMod.PageMod({
include: "*.mozilla.org",
contentScriptFile: [data.url("jquery.min.js"),
data.url("jquery-ui.js"),
data.url("popup.js")]
});
See page-mod manual, it has all needed instructions.

Related

Google One Tap doesn't work on mobile Chrome

I've implemented the Google one tap signin for web using the documentation here, and it works fine on desktop Chrome. However, it doesn't show up at all on iOS Chrome (verison 87) even though I'm signed into Google and the domain is whitelisted.
How do I fix this?
function initialize_google()
{
google.accounts.id.initialize({
client_id: "255011972792-vfp8t4dc4js9perda7aq3f2s6ckjr4p8.apps.googleusercontent.com",
callback: function(credentials) { console.log(credentials) },
context: 'signin',
prompt_parent_id: "g_id_onload"
});
}
function loadScript(url, callback)
{
console.log('in loadScript with url:' + url);
// Adding the script tag to the head as suggested before
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// Then bind the event to the callback function.
// There are several events for cross browser compatibility.
script.onreadystatechange = callback;
script.onload = callback;
// Fire the loading
head.appendChild(script);
}
loadScript("https://accounts.google.com/gsi/client", initialize_google);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Demo</h1>
<div id='g_id_onload'></div>

How to programmatically render dustjs template server side in nodejs

How I can render dustjs template programmatically in nodejs at server side.
dust.render("test", { data: "test" }, function(err, out) {
var datastring = out;
});
which doesn't seems working for me.
You need to make the template available in Node's JavaScript execution environment. Here is an example of how to make that happen:
var fs = require('fs');
var vm = require('vm');
var dust = require('dustjs-linkedin');
// Read the compiled Dust template.
var compiledTemplate = fs.readFileSync('path/to/compiled/dustTemplate.js');
// Execute the compiled Dust template to make it available
// in the current execution context
vm.runInThisContext(compiledTemplate);
// Render the Dust template.
dust.render('test', {data: 'test'}, function(err, out) {
console.log(out);
});

Mozilla Daaon: exchange variables between main.js -> MyContent.js -> MyScripts.js

I' writing a addon that add functionality to a site.
But I need to parse variables between .js
main.js:
pageMod.PageMod({
include: ["*"],
contentScriptWhen: 'end',
contentScriptFile: data.url("MyContent.js"),
contentScriptOptions: {
showOptions: true,
dataUrl: data.url("MyContent.js") // To parse the URL-Path
}
});
MyContent.js:
//to read the URL like resource://.....:
var dataUrl=self.options.dataUrl.substring(0,self.options.dataUrl.lastIndexOf("/")+1)
var script = document.createElement("script");
script.type = "text/javascript";
script.src = dataUrl+"scripts.js";
window.document.head.appendChild(script);
The variable dataUrl exist in MyContent.js but not in MyScripts.js
I need the variable dataUrl in MyScripts.js to know the url for some images saved in the data-folder.
How can I define global variables that can been accessed from all scripts?
with worker can I comunicate between main.js and MyContent.js, but not with MyScripts.js

How to save current document from Firefox Add-on (SDK)?

I would like to save the HTML document in the current tab using a Firefox Add-on created with the Add-on SDK.
I'm trying like this:
exports.main = function() {
require("widget").Widget({
id: "foo",
label: "My Test",
contentURL: "http://www.mozilla.org/favicon.ico",
onClick: function(event) {
var {Cc, Ci} = require("chrome");
var persist = Cc["#mozilla.org/embedding/browser/nsWebBrowserPersist;1"].createInstance(Ci.nsIWebBrowserPersist);
var localPath = Cc["#mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
localPath.initWithPath("/tmp/");
var localFile = localPath.clone();
localFile.append("mylocalfile.html");
var tabs = require("tabs");
persist.saveDocument(tabs.activeTab, localFile, localPath, null, 0, 0);
}
});
};
But the code above crashes Firefox (15.0) when I click on the widget.
I guess that tabs.activeTab might not be a nsIDOMDocument? Is that the problem?
How should I do to make it work?
tabs.activeTab is definitely not an nsIDOMDocument, please see the docs here:
https://addons.mozilla.org/en-US/developers/docs/sdk/latest/packages/addon-kit/tabs.html
You should instead be able to simply open a tab via tabs.open, and attach content scripts to the opened tab. Here is an example of how to attach content scripts to an opened tab:
https://builder.addons.mozilla.org/package/22176/latest/

How to parse a XML string in a Firefox addon using Add-on SDK

I am trying to create a FF AddOn that brings some XML data from a website. But I can't find a way to parse my RESPONSE. First I used DOMParser but I get this error:
ReferenceError: DOMParser is not defined.
Someone suggested to use XMLHttpRequest, because the parsing is done automatically but then I get this other error:
Error: An exception occurred. Traceback (most recent call last):
File
"resource://jid0-a23vmnhgidl8wlymvolsst4ca98-at-jetpack/api-utils/lib/cuddlefish.js",
line 208, in require
let module, manifest = this.manifest[base], requirer = this.modules[base]; TypeError: this.manifest is undefined
I really don't know what else to do. I must note that I am using the AddOn Builder to achieve this.
Below the code that doesn't seem to work.
Option 1:
exports.main = function() {
require("widget").Widget({
id: "widgetID1",
label: "My Mozilla Widget",
contentURL: "http://www.mozilla.org/favicon.ico",
onClick: function(event) {
var Request = require("request").Request;
var goblecontent = Request({
url: "http://www.myexperiment.org/search.xml?query=goble",
onComplete: function (response) {
var parser = new DOMParser();
var xml = parser.parseFromString(response.text, "application/xml");
var packs = xml.getElementsByTagName("packs");
console.log(packs);
}
});
goblecontent.get();
}
});
};
Option 2:
exports.main = function() {
require("widget").Widget({
id: "widgetID1",
label: "My Mozilla Widget",
contentURL: "http://www.mozilla.org/favicon.ico",
onClick: function(event) {
var request = new require("xhr").XMLHttpRequest();
request.open("GET", "http://www.myexperiment.org/search.xml?query=goble", false);
request.send(null);
if (request.status === 200) {
console.log(request.responseText);
}
}
});
};
DOMParser constructor isn't defined in the context of SDK modules. You can still get it using chrome authority however:
var {Cc, Ci} = require("chrome");
var parser = Cc["#mozilla.org/xmlextras/domparser;1"].createInstance(Ci.nsIDOMParser);
nsIDOMParser documentation.
That said, your approach with XMLHttpRequest should work as well. You used the new operator incorrectly however, the way you wrote it a new "require object" is being created. This way it should work however:
var {XMLHttpRequest} = require("xhr");
var request = new XMLHttpRequest();
Please consider using an asynchronous XMLHttpRequest object however, use request.onreadystatechange to attach your listener (the xhr module currently doesn't support other types of listeners or addEventListener).
If you use XMLHttpRequest (available via the xhr module) you can easily avoid the use of DOMParser. Bellow I provide an example supposing request is an XMLHttpRequest object which request is successfully completed:
Instead of:
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(request.responseText, "application/xml");
Use:
var xmlDoc = request.responseXML;
An then you can:
var packs = xmlDoc.getElementsByTagName("packs");
console.log(packs);
Or whatever.

Resources