Page 1 of 2

What am I doing wrong when importing a JS script?

Posted: Fri Feb 19, 2021 2:25 pm
by skinkairewalker
Hello everyone !
there are some Javascript scripts that I try to import into my project, but most of them always get the error> Uncaught ReferenceError, what am I doing wrong when importing these scripts? below an example of the functional html code :

Code: Select all

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link rel="stylesheet" href="https://cdn.metroui.org.ua/v4/css/metro-all.min.css">
  </head>
  <body>
    <h1 class="text-center">Metro 4</h1>
    <h3 class="text-center">The Components Library</h3>
    <div data-role="cube"></div>

    <script src="https://cdn.metroui.org.ua/v4/js/metro.min.js"></script>
  </body>
</html>
But when I try to import the script.js into the SB the error occurs: metro.js: 5450 Uncaught ReferenceError: Metro is not defined
at metro.js: 5450


screenshot : https://prnt.sc/100xl1l

below the SB code that I'm using :

Code: Select all

ExamineDesktops()
Global deskwidth.i = DesktopWidth(0)
Global deskheight.i = DesktopHeight(0)

Declare ButtonClick(index)

Procedure AppendHead(content.s)
  Debug "head"
  !$("head").append(v_content);
EndProcedure

Procedure AppendBody(content.s)
  !$("body").append(v_content);
EndProcedure

Procedure AppendContent(component.i,content.s, Position = #PB_Ignore)
  GID = GadgetID(component)
  If Position <> #PB_Ignore
    ! $(".card:eq(" + v_position + ")").prepend(v_content);
  Else
    ! $(v_gid.div).append(v_content);
  EndIf
EndProcedure

Procedure OnResize()
  
  ExamineDesktops()
  deskwidth = DesktopWidth(0)
  deskheight = DesktopHeight(0)
  
  Debug "Resized W : " + Str(deskwidth)
  Debug "Resized H : " + Str(deskheight)
  
  ResizeWindow(0,#PB_Ignore,#PB_Ignore,deskwidth,deskheight)
  ResizeGadget(0,#PB_Ignore,#PB_Ignore,deskwidth,deskheight)
  
EndProcedure


Procedure Main(URL$, Success)
  
  Debug "Script URL: " + URL$
  Debug "Loading status: " + Success
  
  OpenWindow(0, 0, 0, 600, 600, "",#PB_Window_Background)
  
  ScrollAreaGadget(0, 0, 0, deskwidth, deskheight,600,600) : CloseGadgetList()
  
  AppendContent(0," <h1 class='text-center'>Metro 4</h1>"+
   " <h3 class='text-center'>The Components Library</h3>"+
   " <div Data-role='cube'></div> ") 
  

  
 EndProcedure
    
  Procedure ButtonClick(indice)
    Debug "ButtonClick(" + indice + ")"
  EndProcedure

Procedure init(URL$, Success)
    Debug "Script URL: " + URL$
    Debug "Loading status: " + Success
    
   ; ! $("<link rel='stylesheet' type='text/css'>").attr("href", "https://cdn.metroui.org.ua/v4/css/metro-all.min.css").appendTo("head");

;     ! require(["https://cdn.metroui.org.ua/v4/js/metro.min.js"], function() {
;     Main()
;     ! });    
    
    LoadScript("https://cdn.metroui.org.ua/v4/js/metro.min.js",@Main(),#PB_Script_JavaScript)
    
EndProcedure

BindEvent(#PB_Event_SizeDesktop,@OnResize())

AppendHead("<meta http-equiv='cache-control' content='max-age=0' />' />"+
           "<meta http-equiv='pragma' content='no-cache' />"+
           "<meta http-equiv='cache-control' content='no-store' />"+
           "<meta http-equiv='expires' content='Tue, 01 Jan 1980 1:00:00 GMT' />' />"+
           "<meta http-equiv='expires' content='-1' />")

AppendHead("<meta http-equiv='Content-Security-Policy' content='upgrade-insecure-requests'>")

AppendHead("<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no'>")

;! $("<link rel='stylesheet' href='https://cdn.metroui.org.ua/v4/css/metro-all.min.css' />").appendTo("head");

LoadScript("https://cdn.metroui.org.ua/v4/css/metro-all.min.css", @init(), #PB_Script_CSS)
Can anyone give me a light ? :)

Re: What am I doing wrong when importing a JS script?

Posted: Sat Feb 20, 2021 11:21 am
by Peter
It seems to be a bigger problem to include the metro-library. In an earlier version I managed to do this with the HttpPreProcessor. In the current version, this no longer seems to work.

Re: What am I doing wrong when importing a JS script?

Posted: Tue Apr 06, 2021 9:14 am
by killer128k
Eng: Hello,
In javascript it is possible to add JS script and run it asynchronously when loading a page.php
here is an example.
By loading a main page and adding snippets of code based on visitors' actions.

Fr: Bonjour,
En javascripte il est possible d'ajouter du scripte JS et de l'exécuter de manière asynchrone au chargement d'un page.php
voici un exemple.
En chargeant une page principale et fure à mesure ajouter des bouts de code en fonction des actions des visiteurs.

Code: Select all

<head>
</head>
<body onload="setup()">		
	<div id="profil"></div>
	<script>
		function load_profil(){
			var xmlhttp = new XMLHttpRequest();
			var url = 'profil.php';
			xmlhttp.onreadystatechange = function () {
				if (xmlhttp.readyState == XMLHttpRequest.DONE) {
					if (xmlhttp.status == 200){
						document.getElementById('profil').innerHTML=xmlhttp.responseText;
						execjs('Dyn_profil.js',document.getElementById('profil'));
						....
					}else if (xmlhttp.status == 400) {
						document.getElementById('profil').innerHTML = 'Appel XMLhttp ->Il y a l\'erreur :400.';
					}else{
						document.getElementById('profil').innerHTML = 'Appel XMLhttp ->Il y a une autre erreur que :200.';
			}	}	};
			xmlhttp.open("GET", url, true);
			xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded charset=utf-8");
			xmlhttp.send();	
		}
		window.onload=function(){	load_profil();		}
	</script>
</body>

Re: What am I doing wrong when importing a JS script?

Posted: Tue Apr 06, 2021 9:25 am
by killer128k
Eng:
If you request a file remotely you may encounter "Blocking a Cross-Origin Request".
Launch the application you created on your server where the file in question is located and it should work.
If you launch it locally or from another site you may have trouble getting your request to swallow your internet browser.
The creators of spiderbasic are doing great, by making the software, when you create an app on the phone, they remove the blocking of requests (Cross-Origin Request).

Fr:
Si tu demande un fichier à distance tu risque de te confronté à "Blocage d’une requête multiorigines (Cross-Origin Request)".
Lance l'application que tu as crée sur ton serveur ou est situé le fichier en question et sa devrai fonctionner.
Si tu le lance en local ou depuis un autre site tu risque d'avoir du mal à faire avaler ta requete à ton navigateur internet.
Les créateurs de spiderbasic on fait fort, en fabriquant le logiciel, quand tu crée une app sur téléphone, ils on enlever le blocage des requetes (Cross-Origin Request).

Re: What am I doing wrong when importing a JS script?

Posted: Thu May 27, 2021 4:47 pm
by the.weavster
I have found how to import Metro UI.

It's another library that detects define in the global namespace and it's that that interferes with LoadScript() so what I have done is temporarily hidden define until the imports are completed:

Code: Select all

Global nLoaded
Global nImports = 2

Procedure Main()
  EnableJS
  var btn = document.createElement('button');
  btn.id = 'btn1';
  m4q('body').css('padding', '20px');
  m4q('body').append(btn);
  m4q('#btn1').text('Click Me!');
  m4q('#btn1').addClass('button primary');
  m4q('#btn1').click(function() { 
    var options = { showTop: true, timeout: 3000 };
    Metro.toast.create("Hello, Metro!", null, null, null, options);
  });
  DisableJS
EndProcedure

Procedure Define_Disable()
  EnableJS
  window['hide-define'] = null;
  if(typeof define === 'function' && define.amd) {
    window['hide-define'] = define;
    define = null;
  }  
  DisableJS
EndProcedure

Procedure Define_Enable()
  EnableJS
  if(window['hide-define'] != null) {
    define = window['hide-define'];
    window['hide-define'] = null;
  }
  DisableJS
EndProcedure

Procedure ScriptLoaded(URL$, Success)
  If Success
    nLoaded + 1
    If nLoaded = nImports ; the number of files to import
      Define_Enable() ; our imports have completed so restore define
      Main()
    EndIf
  Else
    Debug "Failed to load external: " + URL$
  EndIf
EndProcedure

Define_Disable() ; temporarily move define so it doesn't interfere with our imports
LoadScript("https://cdn.metroui.org.ua/v4/css/metro-all.min.css", @ScriptLoaded(), #PB_Script_CSS)
LoadScript("https://cdn.metroui.org.ua/v4/js/metro.min.js", @ScriptLoaded())

Re: What am I doing wrong when importing a JS script?

Posted: Thu May 27, 2021 8:02 pm
by Paul
the.weavster wrote: Thu May 27, 2021 4:47 pm I have found how to import Metro UI.

It's another library that detects define in the global namespace and it's that that interferes with LoadScript() so what I have done is temporarily hidden define until the imports are completed:
When I run this code I get an empty browser screen ;(


Browser Dev Tools shows
Uncaught SyntaxError: Unexpected token '{' spiderbasic.js:279

Re: What am I doing wrong when importing a JS script?

Posted: Thu May 27, 2021 8:12 pm
by the.weavster
Paul wrote: Thu May 27, 2021 8:02 pm Browser Dev Tools shows
Uncaught SyntaxError: Unexpected token '{' spiderbasic.js:279
That's because the SB IDE has altered the case of the JavaScript code.
You have to go to:
Preferences->Editor->Editing->Enable Case Correction
to stop it doing that (untick the checkbox)

Re: What am I doing wrong when importing a JS script?

Posted: Thu May 27, 2021 8:47 pm
by Peter
the.weavster wrote: Thu May 27, 2021 4:47 pmI have found how to import Metro UI. [...]
Kudos! Thank you for this elegant code snippet. This opens up a new world for us SpiderBasic programmers. Image

Greetings ... Peter

Re: What am I doing wrong when importing a JS script?

Posted: Fri May 28, 2021 4:56 am
by Paul
the.weavster wrote: Thu May 27, 2021 8:12 pm That's because the SB IDE has altered the case of the JavaScript code.
Ah... thanks !

Re: What am I doing wrong when importing a JS script?

Posted: Fri May 28, 2021 1:28 pm
by Fred
Nice !