Communication between iframe and parent window [JavaScript]

In the iframe you’ll use the below code:

window.parent.postMessage("Hello World !", "http://your.site.web");

And in the parent window:

// function that will be called when the message is received
function receiveMessage(event) {
  alert(event.data); // it'll show "Hello World !"
}
// we listen to a message
if (window.addEventListener) {
  window.addEventListener('message', receiveMessage, false);
} else if (window.attachEvent) { // IE8
  window.attachEvent('onmessage', receiveMessage);
}

It’s working from IE8+, and all modern browsers, but make sure you have a HTML5 doctype (<!DOCTYPE html>)

Use hash word in the Sharepoint navigation

Let’s say you have the url http://my.site.com/myfolder/mypage.aspx#hash and you want to use it as a link into your left navigation bar in Sharepoint…. If you try putting that name, Sharepoint will not keep your link.

The trick here is to add a questionmark juste before the #. The URL to use will be http://my.site.com/myfolder/mypage.aspx?#hash and Sharepoint will accept the link 🙂

How to edit the default action for an icon in a Sharepoint Ribbon

I wanted to change the behavior of the « Edit Item » button from the Sharepoint 2010 ribbon of the Display Form (DispForm.aspx). It wasn’t really easy, so I finally found a solution that I’m going to share here.

You’ll need to use JavaScript for that. In the below example, the click on the « Edit Item » will open the EditForm in a new window:

function ribbonIsLoaded() {
  // find the button we want to change
  var a = document.getElementById('Ribbon.ListForm.Display.Manage.EditItem-Large');
  // remove the default action for this button
  Sys.UI.DomEvent.clearHandlers(a)
  // define your own action
  a.setAttribute("onclick","");
  a.setAttribute("target", "_blank");
  a.setAttribute("href", window.location.href.replace(/DispForm.aspx/,"EditForm.aspx").replace(/&IsDlg=1/,""))
}
// Note: 'SOD' is an abbreviation for "Script on Demand"

SP.SOD.executeOrDelayUntilScriptLoaded(function () {
  var pm = SP.Ribbon.PageManager.get_instance();
  pm.add_ribbonInited(function () {
    ribbonIsLoaded();
  });
  var ribbon = null;
  try
  {
    ribbon = pm.get_ribbon();
  } 
  catch (e) {
  }
  if (!ribbon) {
    if (typeof (_ribbonStartInit) == 'function')
    _ribbonStartInit(_ribbon.initialTabId, false, null);
  } 
  else {
    ribbonIsLoaded();
  }
}, 'sp.ribbon.js');

Installer Android KitKat 4.4.4 sur le Sony Xperia Z1 Compact

La dernière version d’Android est disponible pour le Xperia Z1 Compact, et on trouve tous les tutoriaux nécessaires sur http://www.phonandroid.com :

  1. D’abord il faut télécharger la ROM
  2. Ensuite on l’installe
  3. Puis on peut rooter son téléphone
  4. Et enfin on peut installer un recovery

Show/Hide a Sharepoint fields in the NewForm, EditForm and DispForm

With the Sharepoint WebServices it’s possible to hide a field into the NewForm, the Editform and/or the DispForm.
You’ll need to use JavaScript with jQuery and SPServices. It’s the UpdateList service that will do the trick.

Once you have loaded the both librairies you can use the below code:

var fieldsToUpdate = '<Fields>';
fieldsToUpdate += '<Method ID="1"><Field Type="Text" Name="My_x0020_Field" DisplayName="My Field" ShowInDisplayForm="FALSE" ShowInEditForm="FALSE" ShowInNewForm="FALSE"></Field></Method>';
fieldsToUpdate += '</Fields>';

$().SPServices({
  operation: "UpdateList",
  listName: "Name of the list",
  listProperties:"",
  updateFields: fieldsToUpdate,
  newFields: "",
  deleteFields: "",
  listVersion: "",
  completefunc: function (xData, Status){}
});

As explained into this Stackoverflow’s question you must provide a minimum of three mandatory properties, and in this order:

  1. Type
  2. Name
  3. DisplayName

The Type must reflect the type of your field. This information is available into the MSDN documentation. The most common values should be Boolean | Calculated | Choice | Currency | DateTime | Integer | Lookup | LookupMulti | MultiChoice | Number | Text | User | UserMulti.

The Name is the internal name (usually the spaces are replaced with « _x0020_ »).

And for each form (ShowInDisplayForm | ShowInEditForm | ShowInNewForm) you can set them to TRUE or FALSE (it seems to be case sensitive ?!). More properties are available into the MSDN documentation.

Delete a User Custom Action from Sharepoint [JavaScript]

The MSDN documentation is a nightmare…. For example Microsoft provides an example to create a User Custom Action for Sharepoint, however there is no code about how to delete it.

So here is the code to use to delete the usercustomaction just created with the above example:

var siteUrl = '/site collection/site/';

function deleteUserCustomAction() {
    this.clientContext = new SP.ClientContext(siteUrl);
    var oWebsite = clientContext.get_web();
    this.collUserCustomAction = oWebsite.get_userCustomActions();
    clientContext.load(oWebsite,'UserCustomActions','Title');
    clientContext.executeQueryAsync(Function.createDelegate(this, this.deleteCustomAction), Function.createDelegate(this, this.onQueryFailed));
}
function deleteCustomAction() {
    var customActionEnumerator = collUserCustomAction.getEnumerator();
    while (customActionEnumerator.moveNext())  {
      var oUserCustomAction = customActionEnumerator.get_current();
      if (oUserCustomAction.get_title() == 'New Menu Item') {
           oUserCustomAction.deleteObject();        
           clientContext.load(oUserCustomAction);
           clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
        }
    }
}
function onQuerySucceeded() {
    alert('Custom action removed');
}
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
deleteUserCustomAction()

Dynamically inject a CSS code into the page [JavaScript]

Mozilla created a function that permits to inject some CSS into the document: addStylesheetRules()

But if you use jQuery you may want to use this function:

function injectCSS(rule) {
  $("head").append('<style>' + rule + '</style>')
}

// example
injectCSS("div { padding:5px }")

Tiny AJAX

This is a very tiny javascript code to do an AJAX Request:

/*
 m: method ("get", "post")
 u: url
 a: async (true) or sync (false)
 c: callback (with 'xhr' as a parameter)
 d: post_data (the data to post)
*/
function tiny_ajax(m,u,a,c,d){with(new(this.XMLHttpRequest||ActiveXObject)("Microsoft.XMLHTTP"))onreadystatechange=function(){readyState^4||c(this)},open(m,u,a),send(d)}

And an example:

tiny_ajax('get', 'http://www.google.com', true, function(xhr) {
    alert(xhr.responseText)
})

Se connecter à son réseau local via le VPN de la Freebox Revolution

Grâce aux dernières mises à jour de la Freebox Revolution, il est maintenant possible de se connecter à son réseau local depuis l’extérieur. Cela peut être utile pour, par exemple, accéder à un ordinateur de son réseau, etc.

On va d’abord ouvrir l’accès à sa Freebox depuis l’extérieur. Pour ce faire, se rendre sur http://mafreebox.freebox.fr/ puis Paramètres de la Freebox et choisir Gestion des accès. Dans l’onglet paramètres, indiquer un mot de passe, un port et activer l’identification par mot de passe. Conserver l’adresse qui vous est alors fournie. Cette manipulation est utile pour pouvoir accéder à votre Freebox à distance et ainsi faire diverses manipulations.

Maintenant, retourner dans Paramètres de la Freebox puis dans l’onglet Mode Avancé : double-cliquer sur l’icône Serveur VPN.
★ Aller d’abord dans Utilisateurs pour en ajouter un nouveau. Laisser « IP Dynamique ».

Ensuite on a le choix entre trois types de VPN :

  • OpenVPN Bridgé : qui demande l’installation d’un logiciel sur l’ordinateur distant, mais qui permet d’accéder au réseau local autour de la Freebox
  • OpenVPN Routé : qui demande l’installation d’un logiciel sur l’ordinateur distant, mais qui NE permet PAS d’accéder au réseau local autour de la Freebox
  • PPTP : qui peut s’utiliser nativement dans Windows, mais qui NE permet PAS d’accéder au réseau local autour de la Freebox

On trouve plusieurs tutoriaux sur le Net concernant le PPTP. Il est pratique si l’on souhaite accéder seulement au contenu de sa Freebox. Par contre si on souhaite voir les autres ordinateurs de son réseau local il faudra utiliser le mode OpenVPN Bridgé.

Donc aller dans OpenVPN Bridgé, cocher la case pour l’activer, laisser les options par défaut, et appliquer. On va alors avoir un fichier de configuration qui va apparaitre en face du nom d’utilisateur créé précédemment :
20140527_serveur_vpn

★ Cliquer sur l’icône pour télécharger la configuration.

Maintenant il faut installer OpenVPN sur l’ordinateur distant (donc celui à l’extérieur du réseau local). Il n’y a que la version 2.2.2 d’OpenVPN qui a fonctionné chez moi. Elle est disponible sur cette page : https://openvpn.net/index.php/open-source/downloads.html.
Une fois installé, mettre le fichier de configuration téléchargé précédemment dans le répertoire config/ du répertoire d’installation d’OpenVPN. Lancer OpenVPN GUI sur l’ordinateur distant : il devrait demander un nom d’utilisateur et un mot de passe. Il faut entrer le nom d’utilisateur/password créé précédemment.

Si tout se passe bien, la connexion va alors s’établir. Vous aurez ainsi accès à votre réseau local. Par exemple si une de vos machines a l’IP 192.168.0.1, vous pourrez la pinguer, ou vous pourrez la redémarrer.