How to use Rollbar.js in Firefox Extension - javascript

I'm trying to implement rollbar.js to Firefox extentsion. However, there is no possibility to load it within "rollbar snippet" - it loads .js file from cdn - that's not allowed in Firefox addons.
So I reworked it and load rollbar.js from local file. This solution works in Chrome extension, however in Firefox addon I always get "Rollbar is undefined" ..
Here is the simplified code I use in poppup.html...
<script>
chrome.storage.local.get(['optins'], function(value) {
var rollbarOptIn = true;
window._rollbarConfig = {
accessToken: "xxx",
captureUncaught: true,
captureUnhandledRejections: true,
enabled: rollbarOptIn,
payload: {
environment: "{{ ENVIRONMENT }}",
client: {
source_map_enabled: true,
code_version: "{{ VERSION }}",
guess_uncaught_frames: true
}
}
};
});
</script>
<script type="text/javascript" src="scripts/rollbar.js" async="false"></script>
<script>
/* ugly workaround with set timeout... */
setTimeout(function(){
...
Rollbar.error("test");
...
}, 600);
</script>
I am in the end.. please help.

Since chrome.storage is asynchronous its callback runs after rollbar.js so you probably have a browser-specific race condition between an asynchronous initialization in rollbar and that callback.
Remove <script> from your HTML and try loading it dynamically, then use its onload event:
chrome.storage.local.get('optins', ({optins}) => {
window._rollbarConfig = {
// ...............
};
const el = document.createElement('script');
el.src = 'scripts/rollbar.js';
el.onload = useRollbar;
document.documentElement.appendChild(el);
});
function useRollbar() {
Rollbar.error("test");
// ...............
}

Related

codemirror.setOption('mode',val) isnt working

I am trying to make a text editor with firepad and codemirror, everything works perfectly on page loading, but when I try to change the mode on button click, the function gets called but
codemirror.setOption('mode',val);//should change mode
CodeMirror.autoLoadMode(editor, mode);//should reload codemirror
doesn't seem to work.
I am calling the following code on the onload event of the body (works perfectly):
var firepadRef = getExampleRef();
codeMirror = CodeMirror(document.getElementById('firepad-container'), {
lineNumbers: true,
mode: 'javascript'
});
var firepad = Firepad.fromCodeMirror(firepadRef, codeMirror, {
defaultText: '// Welcome'
});
function getExampleRef() {
var ref = database.ref('Firepad');
var hash = window.location.hash.replace(/#/g, '');
if (hash) {
ref = ref.child(hash);
} else {
ref = ref.push(); // generate unique location.
window.location = window.location + '#' + ref.key;
}
if (typeof console !== 'undefined') {
console.log('Firebase data: ', ref.toString());
}
return ref;
}
on button click event I am calling the following code (problem here!):
console.log('Button Clicked');
CodeMirror.modeURL = "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.40.0/mode/%N/%N.js";
var editor = CodeMirror(document.getElementById('firepad-container'), {
lineNumbers: true
});
console.log("started changing");
var val ="xml",mode,spec;
mode=spec=val;
editor.setOption("mode", spec);//isn't changing mode!!
CodeMirror.autoLoadMode(editor, mode);//isn't reloading editor!!
This is just a miniaturized sample of the code (the relevant one).
I am using as a resources for the mode reloading and for firebase with codemirror the following:
https://firepad.io/docs/
https://codemirror.net/demo/loadmode.html#
Scripts and stylesheets being called are the following (the relevant ones only):
<link rel="stylesheet" href="codemirror-dark.css">
<link rel="stylesheet" href="https://cdn.firebase.com/libs/firepad/1.4.0/firepad.css">
<script src="https://www.gstatic.com/firebasejs/5.0.4/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.2.0/firebase-database.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.40.0/codemirror.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.40.0/addon/mode/loadmode.js"></script>
<script src="https://cdn.firebase.com/libs/firepad/1.4.0/firepad.min.js"></script>
I am using Firefox and there is no errors on the developper console(it is just neither changing nor reloading).
So what am I missing ??
Thanks in advance.
codemirror doesn't accept "xml" as a mode type. What you're looking for is "application/xml" or "text/xml".
according to the documentation on CodeMirrors site, you need to call codemirror.findModeByExtension on your filename string's extension to get an info object. You call CM_OBJ.setOption("mode",info.mime) first, then CodeMirror.autoLoadMode(editor,info.mode) if you want to use simpler and less specific typing strings.
this works for me on firefox and chrome from the inspect page.
source: https://codemirror.net/demo/loadmode.html

Client Side Taxonomy Picker For SharePoint

On Premise SharePoint 2013, Implementing a Client Side Taxonomy Picker For SharePoint using below blogs:
https://www.c-sharpcorner.com/UploadFile/93cb27/client-side-taxonomy-picker-for-sharepoint-app/
https://blogs.msdn.microsoft.com/richard_dizeregas_blog/2014/03/13/taxonomy-picker-in-sharepoint-provider-hosted-app/
Added the code using a Script Editor, and the control shows only on Edit Mode - when I save the page, the control disappears and throws the following error "b.get_path is not a function"
Tried many combinations however it looks like a bug as the same code works fine in SharePoint Online.
<link href="https://server/sites/TeamSite/SiteAssets/CodeLibrary/styles/taxonomypickercontrol.css" rel="stylesheet"/>
<script type="text/ecmascript" src="https://server/sites/TeamSite/SiteAssets/CodeLibrary/jquery-1.9.1.js"></script>
<script type="text/ecmascript" src="https://server/sites/TeamSite/SiteAssets/CodeLibrary/taxonomypickercontrol.js"></script>
<script type = "text/javascript" src = "https://server/sites/TeamSite/SiteAssets/CodeLibrary/taxonomypickercontrol_resources.en.js"></script>
<script type = "text/javascript" src = "https://server/sites/TeamSite/_layouts/15/sp.core.js" ></script>
<script type = "text/javascript" src = "https://server/sites/TeamSite/_layouts/15/sp.runtime.js" ></script>
<script type = "text/javascript" src = "https://server/sites/TeamSite/_layouts/15/sp.taxonomy.js" ></script>
<script type = "text/javascript">
if (myStronglyTypedObj === undefined) {
var myStronglyTypedObj = {};
}
myStronglyTypedObj = {
// Object Globals
"g": {},
// Pre-initialization functions ensure scripts SharePoint dependencies are loaded
"preinit": function() {
// Load necessary libraries
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {
// Register what you need from SharePoint (in this case the sp.runtime)
SP.SOD.registerSod('sp.runtime.js', SP.Utilities.Utility.getLayoutsPageUrl('sp.runtime.js'));
// Register what you need from SharePoint (in this case the term store)
SP.SOD.registerSod('sp.taxonomy.js', SP.Utilities.Utility.getLayoutsPageUrl('sp.taxonomy.js'));
// Load the registered items
SP.SOD.executeFunc('sp.taxonomy.js', 'SP.Taxonomy.TaxonomySession', myStronglyTypedObj.init());
});
},
// The main Initialization function
"init": function() {
/* Check if SP.Taxonomy actually exists yet
* PLEASE NOTE that it's common that these objects aren't available, even if you've properly loaded them in the "preinit" function.
* This bit of code checks if the object is available, and if it's not, waits for 200ms and then tries again until this object is loaded
*/
if (SP.Taxonomy) {
console.log("SP.Taxonomy ready... continuing scripts...");
myStronglyTypedObj.therest();
} else {
console.log("SP.Taxonomy not ready... set timeout and try again after 200ms");
setTimeout(myStronglyTypedObj.init, 200);
}
},
"therest": function() {
// Continue with your code here...
try {
var context = new SP.ClientContext()
$('#taxPickerKeywords').taxpicker({ isMulti: true, allowFillIn: true, termSetId: "63858201-dd9b-46b1-b1bb-b6a054fa7cb7" }, context);
}
catch(err) {
alert(err.message);
}
}
}
$(document).ready(function(){
myStronglyTypedObj.preinit();
});
</script>
<div>
<input type="hidden" id="taxPickerKeywords" />
</div>
As stated it works in SharePoint Online, though I checked the version of our Farm and it seems that our dev box was not up to date.
After patching, it worked fine.
Thanks for your valuable help.

window.location.replace wtih Phonegap

I try setup a JS function to auto load a index page in a different language, regardig the setting device o my reader.
I try with this...but don't work :
<script src="cordova-2.2.0.js"></script>
<script type="text/javascript" charset="utf-8">
function checkLanguage() {
if (navigator.globalization.getPreferredLanguage()='en_EN')
{
window.location.replace("index_en.html");
}
else if (navigator.globalization.getPreferredLanguage()='fr_FR')
{
window.location.replace("index_fr.html");
}
else
{
window.location.replace("index_other.html");
}
}
</script>
Is this method can be use, or do I have to consider other option to deal with my multilanguage app ?
Thanks in advance for any help.
You need to use the callback of getPreferredLanguage:
var handleDeviceReady = function (event)
{
navigator.globalization.getPreferredLanguage(
function (language)
{
console.log("language: " + language.value + '\n');
redirectToLocaleSpecificLogin(language.value);
},
function ()
{
console.log("Error getting language\n");
redirectToLocaleSpecificLogin("en");
}
);
};
document.addEventListener("deviceready", handleDeviceReady, false);
Then inside of your callback (redirectToLocaleSpecificLogin in this case), you can do your redirects.
most of the browsers use language property, IE uses userLanguage
var lang = window.navigator.userLanguage || window.navigator.language;
this should work in IE, SAFARI, CHROME and FF
Edit:
JavaScript for detecting browser language preference this link has more detailed discussion on this topic

conditionally loading external javascript libraries in my plugin

I have written a plugin that depends on external libraries that I want to include conditionally, that is, the user can choose to not have them be included automatically in case the user's web site already has those libraries. Here is some pseudocode to illustrate the issue
<script type="text/javascript" src="path/to/plugin.js"></script>
<script type="text/javascript">
PLUGIN.init({
"param1": "foo",
"parma2": 33,
"include": {"jquery": 0, "googlemaps": 0}
});
</script>
In my plugin script
var PLUGIN = {
"init": function(obj) {
if (obj.include.googlemaps !== 0) {
document.write('<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&v=3.6">\x3C/script>');
}
if (obj.include.jquery !== 0) {
document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js">\x3C/script>');
}
.. do more things ..
}
The problem is that when I am ready to "do more things," the libraries don't seem to be loaded yet. I get an error that jquery not found, or google maps not found. I can solve this by changing my code to
document.write('<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&v=3.6">\x3C/script>');
document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js">\x3C/script>');
var PLUGIN = {
"init": function(obj) {
.. do more things ..
}
but now the user can't control loading the libraries or not loading them. Suggestions? Workarounds?
Update: Thanks for the suggestions, you all, but no joy so far. Here is what I am doing, and what is happening. Since I am potentially loading 0 or more scripts (the user can optionally decide which scripts need not be loaded), I have made my code like so
"importLib": function(libPath, callback) {
var newLib = document.createElement("script");
if (callback !== null) {
newLib.onload = callback;
}
newLib.src = libPath;
document.head.appendChild(newLib);
},
"init": function(obj) {
var scripts = [];
if (obj.include.googlemaps !== 0) {
scripts.push("http://maps.google.com/maps/api/js?sensor=true&v=3.6");
}
if (obj.include.jquery !== 0) {
scripts.push("http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js");
}
if (obj.include.anotherlib !== 0) {
scripts.push("http://path/to/another/lib.js");
}
var len_scripts = scripts.length,
callback = null;
if (len_scripts > 0) {
for (var i = 0; i < len_scripts; i++) {
// add callback only on the last lib to be loaded
if (i == len_scripts - 1) {
callback = function() { startApp(obj) };
}
importLib(scripts[i], callback);
}
}
// Start the app rightaway if no scripts need to be loaded
else {
startApp(obj);
}
},
"startApp": function(obj) {
}
What happens is that Firefox croaks with a attempt to run compile-and-go script on a cleared scope error, and Safari doesn't get that error, but doesn't load anything. Funnily, Safari error console shows no error at all. Seems like the Firefox error is caused by the line document.head.appendChild(newLib); which, if I comment, the error goes away, but of course, the web page doesn't load correctly.
You should add each script as a DOM node and use the onload attribute to take action when it has completed loading.
function importLib(libPath, callback) {
var newLib = document.createElement("script");
newLib.onload = callback;
newLib.src = libPath;
document.head.appendChild(newLib);
}
Above, the libPath argument is the URL of the library, and the callback argument is a function to call when loading is complete. You could use it as follows:
importLib("http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js", function() {
alert("jquery loaded!");
nowDoSomething(aboutIt);
});
By the way: in general, document.write is not a good solution for most problems (but I won't say never the right solution -- there are exceptions to every rule).
the above solution would work in modern browsers but for IE 7/8 u might wanna added little extra code, something like this:
function importLib(libPath, callback) {
var newLib = document.createElement("script");
if (navigator.userAgent.indexOf('MSIE') !== -1) {
newLib.onreadystatechange = function () {// this piece is for IE 7 and 8
if (this.readyState == 'complete') {
callback();
}
};
} else {
newLib.onload = callback;
}
newLib.src = libPath;
document.head.appendChild(newLib);
}
I encountered the same issue. One workaround if you are writing your site in .NET is by conditionally writing the script reference before the page loads from the code behind. My issue is when remote users access my app over VPN, it blocks access to the internet, thus google maps cannot be referenced. This prevents the rest of the page from loading within a reasonable timeframe. I tried controlling the script reference of the google maps library via jQuery's getScript() command, but as you found out, the subsequent google maps configuration code runs before the external library is referenced.
My solution was to conditionally reference google maps from code behind instead:
VB (code behind):
'if VPN mode is not enable, add the external google maps script reference (this speeds up the interface when using VPN significantly)
If Session("VPNMode") = False Then
Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder()
sb.AppendLine("")
sb.AppendLine("<script type='text/javascript'")
sb.Append(" src='http://maps.google.com/maps/api/js?v=3&sensor=false'>")
sb.Append("</script>")
Dim header As LiteralControl = New LiteralControl
header.Text = sb.ToString()
Me.Page.Header.Controls.Add(header)
End If
Client side script (javascript):
<script type='text/javascript'>
$(function () {
if ($("input[name*='VPN']").is(":checked"))
{ }
else {
loadGoogleMap()
}
});
function loadGoogleMap() {
hazsite = new google.maps.LatLng(hazLat, hazLong);
map = new google.maps.Map(document.getElementById('map_canvas'), { zoom: 18, center: hazsite, mapTypeId: google.maps.MapTypeId.SATELLITE });
var marker = new google.maps.Marker({
position: hazsite,
map: map,
title: "Site Location"
});
}
</script>

EasyXDM ErrorHandler gets executed twice on Firefox only

I use easyXDM to make cross-domain POST request and receive a response. When the request reaches a timeout, easyXDM executes the ErrorHandler function twice when I run it on Firefox. On Chrome and IE7 it works fine (i.e. just one execution). Why is that? Any ideas how can I prevent it?
Firefox version 6.0.2
EasyXDM version 2.4.15.118
Hosted on IIS
Example code (this works as described above on my computer, the "Error" alert appears twice on Firefox and once on Chrome and IE7): (obviously, the timeout is set so low so that it would always happen)
<html>
<head>
<script type="text/javascript" src="easyXDM.js"></script>
<script type="text/javascript">
var rpc = new easyXDM.Rpc({
remote: "http://myserver.com/Cors.html"
}, {
remote: {
request: {}
}
});
request = {
url: "http://myserver.com/DoSomething.aspx",
method: "POST",
timeout: 1,
data: {
SomeData: "SomeInformation"
}
};
var responseHandler = function(response) {
alert("Responded");
};
var errorHandler = function(error) {
alert("Error");
};
rpc.request(request, responseHandler, errorHandler);
</script>
</head>
<body>
</body>
This was fixed in https://github.com/oyvindkinsey/easyXDM/commit/c6da9f074606f153769d8be61aca804a02a7acb9
based on the discussion in https://groups.google.com/forum/#!topic/easyxdm/DI470RVe8hk

Categories