• Home
  • Categories
  • Recent
  • Popular
  • Top
  • Tags
  • Users
  • Groups
  • Documentation
    • Home
    • Read API
    • Write API
    • Plugin Development
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
v3.5.1 Latest
Buy Hosting

Add js file before loading/rendering header.tpl in middleware

Scheduled Pinned Locked Moved General Discussion
ajaxheadernodebb
5 Posts 3 Posters 4.5k Views
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • kimmanuelK Offline
    kimmanuelK Offline
    kimmanuel
    wrote on last edited by
    #1

    Is this possible? Because I have a problem, in my header.tpl, I included script that gets/sets token and request for logged in user from different server, the problem is that I have to refresh the page twice so that the isLoggedIn validation in menu.tpl will be TRUE, because in actual, the first time I load the page Header.tpl, menu.tpl is already loaded then ---> will read get/set token --> refresh page twice (must be refreshed only once):

    Is there a way that script file for get/set token will be loaded first before the renderHeader in middleware.js?

    This is my script:

    **<script>
    //START TOKEN
    var _session = {};
    var domain = config_ws.cookieUrl? 'domain='+config_ws.cookieUrl+';': '';
    var dmName = document.createElement("input");
    dmName.setAttribute('type', 'hidden');
    dmName.setAttribute('value', domain);
    dmName.setAttribute('id', 'domainValue');
    _session.setToken = function(t) {
    // we won't be using the $cookie service when setting the token
    // because it doesn't allow setting the domain

    	      if (!t || t == '') {
    	        //$cookies.accessToken = '';
    	        document.cookie = 'accessToken=; expires=Thu, 01 Jan 1970 00:00:00 GMT; '+domain+' path=/';
    	      } else {
    	        //$cookies.accessToken = t;
    	        document.cookie = 'accessToken='+t+'; expires=0; '+domain+' path=/';
    	      }
    	    };
    	    _session.getToken = function() {
    	      /*if ($cookies.accessToken && $cookies.accessToken != '') {
    	        return $cookies.accessToken;
    	      } else {
    	        return '';
    	      }*/
    	      var match = document.cookie.match(new RegExp('accessToken=([^;]+)'));
    	      return match && match[1]? match[1]: '';
    	    };
    	    _session.hasToken = function() {
    	      return _session.getToken().length > 0? true: false;
    	    };
    
    		var csrf = $('#csrf_token').val();
    		var userLoggedIn = $('#user_loggedin').val();
    		if(userLoggedIn == "true") {
    			var userWsid = $('#user_wsid').val();
    			if(userWsid == 0) { // means user logged in is a NodeBB User
    				// level of priority NodeBB User
    			} else {  // means user logged in is from WS
    				setUserToken();
    			}
    		} else {
    			setUserToken();
    		}
    		
    		function setUserToken() { // means user logged in is from WS
    			if(_session.hasToken() == true) {
    					$.ajax({
    						type: "GET",
    						beforeSend: function (request)
    						{
    		            		request.setRequestHeader("Authorization", "Bearer " + _session.getToken());
    		        		},
    						url: config_ws.wsBaseUrl + "/api/user/get",
    						success: function(wsuser) {
    								// console.dir(wsuser);
    
    								//get billing info
    								$.ajax({
    									type: "GET",
    									beforeSend: function (request)
    									{
    					            		request.setRequestHeader("Authorization", "Bearer " + _session.getToken());
    					            		_session.setToken(_session.getToken());
    					        		},
    									url: config_ws.wsBaseUrl + "/api/user/billing-info?userId=" + wsuser.userId,
    									success: function(wslocation) {
    										// create or update ws user
    										$.ajax({
    											type: "POST",
    											data:{user: wsuser, _csrf: csrf, wsBaseUrl: config_ws.wsBaseUrl, wsuserlocation: wslocation},
    											url: RELATIVE_PATH + '/api/wsuser',
    											cache: false,
    											success: function(res) {
    													// if (previousUrl) {
    													// 	app.previousUrl = previousUrl;
    													// } else if (!app.previousUrl) {
    													// 	app.previousUrl = '/';
    													// }
    
    												//window.location.replace(window.location.pathname);
    												app.loadConfig();
    											},
    											complete: function() {
    								                setTimeout(setUserToken,1000); //After completion of request, time to redo it after a second
    								            },
    											error: function() {
    												console.log("error-post");
    											},
    											dataType: 'json',
    										 	async: true
    										});
    									}
    								});
    						},
    						error: function(request,error) {
    							console.log(error);
    						},
    						dataType: 'json',
    					 	async: true
    					});
    
    			} else {
    				if(userLoggedIn == "true") {
    					$.post(RELATIVE_PATH + '/logout', {
    						_csrf: $('#csrf_token').val()
    					}, function() {
    						if(window.location.pathname != RELATIVE_PATH + '/') {
    							window.location.href = RELATIVE_PATH + '/';
    						}
    						
    					});
    				}
    			}
    		}
    		
    		// END TOKEN
    	</script>
    

    **

    Thank You! 🙂

    A 1 Reply Last reply
    0
  • A Offline
    A Offline
    a_5mith
    replied to kimmanuel on last edited by a_5mith
    #2

    @kimmanuel

    Create a plugin.json file in your theme and add a link to the file that contains your JS. See link below.

    Then create a folder called lib inside a folder called static, then a new file called main.js. Paste your script in there, and it will be minified along with the core code on startup.

    See plugin.json

    and main.js

    be sure to include use strict.

     "use strict";
    your code goes here without the script tags
    }());
    
    kimmanuelK 1 Reply Last reply
    0
  • psychobunnyP Offline
    psychobunnyP Offline
    psychobunny
    wrote on last edited by
    #3

    You're missing the

    (function() {
    

    (My turn to troll you)

    A 1 Reply Last reply
    0
  • kimmanuelK Offline
    kimmanuelK Offline
    kimmanuel
    replied to a_5mith on last edited by kimmanuel
    #4

    @psychobunny @a_5mith Does the .js file here loaded only once when I start nodebb? Whenever I want to refresh the page, it must be load again the js file right? Is this what will happen in creating the plugin?

    Thanks! 🙂

    1 Reply Last reply
    0
  • A Offline
    A Offline
    a_5mith
    replied to psychobunny on last edited by
    #5

    @psychobunny good point. 😆

    1 Reply Last reply
    0

Copyright © 2023 NodeBB | Contributors
  • Login

  • Don't have an account? Register

  • Login or register to search.
Powered by NodeBB Contributors
  • First post
    Last post
0
  • Home
  • Categories
  • Recent
  • Popular
  • Top
  • Tags
  • Users
  • Groups
  • Documentation
    • Home
    • Read API
    • Write API
    • Plugin Development