I created a script that add javascript files by appending it to the head tag.
Using the code below that I created:
var Dim = (function(s){
var storage;
function loadError (oError) {
throw new URIError("The script " + oError.target.src + " is not accessible.");
}
return {
require : function(script,callback){
var oScript = document.createElement("script");
oScript.type = "text\/javascript";
oScript.onerror = loadError;
if (callback) {
oScript.onload = callback;
}
document.head.appendChild(oScript);
oScript.src = script;
}
};
})();
When we use the script like this:
Dim.require("script.js", function(){alert(token)}); alert(token);
and script.js code is:
alert(" Ok"); var token = " Hello";
The alert(token) throws an error.
Can anyone point me the Problem?
[Question was edited]
Dim.require("script.js", function(){alert(token)}); alert(token);
It runs first alert because its in callback which is called when the script is loaded by the browser.
if (callback) {
oScript.onload = callback;
}
And second is not giving you an alert because it gives you an error
Uncaught ReferenceError: token is not defined
You are loading your script.js asynchronously and while executing second alert , the script.js not loaded yet.
Related
This is my custom code for a website:
<script>
function showCookieBanner () {
//check lang_id
var policy_id = 0;
var lang_id = jQuery('html').attr('lang').split('-')[0];
console.log(lang_id);
if (lang_id === 'en') {
policy_id = myID;
}
else if (lang_id === 'de') {
policy_id = myID;
}
console.log(policy_id)
//declare Variable for external script (_iub)
var _iub = _iub || [];
_iub.csConfiguration = {
"lang": lang_id,
"siteId": mySiteID,
"cookiePolicyId": policy_id,
};
//run external script:
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.src= '//cdn.iubenda.com/cs/iubenda_cs.js';
script.type='text/javascript';
script.charset='UTF-8';
head.appendChild(script);
}
window.addEventListener('load', showCookieBanner);
</script>
With this script, I try to implement a cookie-banner solution from iubenda.
First the lang_id of the HMTL document is checked. With the lang_id the policy_id is determined. And then passed to the variable _iub. The variable _iub is needed by the external script (see comment in the code).
The whole thing has to happen when everything is loaded, so I use "window.addEventListener('load', showCookieBanner)".
Getting the lang_id and policy_id works (was checked with console.log), but I get the following error message, when I load the page:
iubenda_cs.js:1 Uncaught ReferenceError: _iub is not defined
at iubenda_cs.js:1
at iubenda_cs.js:1
(anonymous) # iubenda_cs.js:1
(anonymous) # iubenda_cs.js:1
Try to declare the '_iub' variable as global one, like this:
var _iub = _iub || [];
function showCookieBanner () {
...
}
I am trying to use SignalR for ASP.NET Core 2.0, but when I try to implement the SignalR client in my View, I get the error that the variable "signalR" is undefined despite auto-completion working fine in my editor, Here is the script :
<script type="text/javascript">
var _transport = signalR.TransportType.WebSockets; //HERE
var connection = new signalR.HubConnection(`http://${document.location.host}/chat`, {transport: _transport});
var messageInput = document.getElementById('message');
var name = '#User.Identity.Name';
var button = document.getElementById('sendMessage');
connection.on('broadcastMessage', (name, message) => {
var text = document.createElement('p');
text.innerHTML = '<strong>' + name + '</strong>' + " : " + message;
document.getElementById('messageArea').appendChild(text);
});
button.addEventListener("click", event => {
connection.invoke('send', name, messageInput.value);
messageInput.value = '';
messageInput.focus();
});
connection.start();
I have added the signalr.js in my _Layout.cshtml
Here is the tree structure of my wwwroot where I've added the .js files for signalr :
And finally, here is the debugger structure in Firefox where I can see that the signalr.js has been loaded, and so are jQuery and bootstrap..
So why is "signalR" undefined? What am I missing? Is it because I've added the signalr javascript files manually in my project? (Probably...)
I think your script is executed before the signalr.js is loaded. Try to use an event to execute your code. IF we do this on document load then we'll be sure that it's defined.
$(document).load(function(){
// your code here
});
Here is my code, I have included following .js files, onpage load it is giving error "ReferenceError: CryptoJS is not defined" why does it give that error when already js references are added. I am making a sharepoint-2013 app using office 365.
<script type="text/javascript" src="../Scripts/sha1.js"></script>
<script type="text/javascript" src="../Scripts/hmac-sha1.js"></script>
'use strict';
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
(function () {
// This code runs when the DOM is ready and creates a context object which is
// needed to use the SharePoint object model
$(document).ready(function ()
{
getUserName();
$("#button1").click(function()
{
paraupdate();
});
});
// This function prepares, loads, and then executes a SharePoint query to get
// the current users information
function paraupdate()
{
var str=""+$("#textbox1").val();
alert(""+str);
var message = str+"json539ff0f815ca697c681fe01d32ba52e3";
var secret = "<my private key>";
var crypto = CryptoJS.HmacSHA1(message, secret).toString();
alert("crypto answer is " + crypto);
var siteurl="http://pnrbuddy.com/api/station_by_code/code/"+str+"/format/json/pbapikey/539ff0f815ca697c681fe01d32ba52e3/pbapisign/"+crypto;
$.ajax({
url: siteurl,
type: "GET",
dataType: 'json',
success: function (data) {
alert("IN Success");
alert(""+data.station_by_code);
},
error: function (error) {
alert("IN Error");
alert(JSON.stringify(error));
}
});
}
function getUserName()
{
context.load(user);
context.executeQueryAsync(onGetUserNameSuccess, onGetUserNameFail);
}
// This function is executed if the above call is successful
// It replaces the contents of the 'message' element with the user name
function onGetUserNameSuccess()
{
$("#label1").html("Enter Station Code : ");
$("#button1").val("CLICK");
}
// This function is executed if the above call fails
function onGetUserNameFail(sender, args) {
alert('Failed to get user name. Error:' + args.get_message());
}
})();
include core-min.js before sha256.js
There are one of two forms for fixing this:
1: Manual Load, i have more success with this pattern:
$.getScript(scriptbase + "SP.Runtime.js",
function () {
$.getScript(scriptbase + "SP.js", execOperation);
}
);
Example:
$.getScript("~hostUrl/_layouts/15/SP.RequestExecutor.js", getListDataREST);
2: Script on Demand:
SP.SOD.executeFunc('sp.userprofiles.js', 'SP.ClientContext', loadUserData);
This SharepointExchange posting, gives the usual JSOM implementation for most AppParts: Jquery is not firing on Page load SharePoint 2013
Error solved I added online references instead,
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha1.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/hmac-sha1.js"></script>
Maybe is too late, but:
var CryptoJS = require('crypto-js');
var hash = CryptoJS.HmacSHA256("Message", "secret");
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
console.log(hashInBase64); // qnR8UCqJggD55PohusaBNviGoOJ67HC6Btry4qXLVZc=
Works fine in node.js.
When using server and client in same machine by ajax connectivity it shows the inactive state of server. On using dynamic script tag it doesn't reflect the inactivness of server. How could this be resolved?
we have included these functions in a .js file.
function JSONscriptRequest(fullUrl) {
this.fullUrl = fullUrl;
this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
this.headLoc = document.getElementsByTagName("head").item(0);
this.scriptId = 'JscriptId' + JSONscriptRequest.scriptCounter++;
}
JSONscriptRequest.scriptCounter = 1;
JSONscriptRequest.prototype.buildScriptTag = function () {
this.scriptObj = document.createElement("script");
this.scriptObj.setAttribute("type", "text/javascript");
this.scriptObj.setAttribute("charset", "utf-8");
this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
this.scriptObj.setAttribute("id", this.scriptId);
}
JSONscriptRequest.prototype.removeScriptTag = function () {
this.headLoc.removeChild(this.scriptObj);
}
JSONscriptRequest.prototype.addScriptTag = function () {
this.headLoc.appendChild(this.scriptObj);
}
and used the following code in jsp page
// The web service call
var req = <<<url of the service which resides in different server>>>&callback=<callback function>;
// Create a new request object
bObj = new JSONscriptRequest(req);
// Build the dynamic script tag
bObj.buildScriptTag();
// Add the script tag to the page
bObj.addScriptTag();
I am busy developing a firefox extension. I am using the Add-on Builder
What it will do:
Get an ID from a PHP page (XMLHttpRequest)
Call another function and send that ID with it
That function inserts CSS with a link tag created by javascript
My Problem:
It won't work. If I alert the currenttheme variable, nothing happens. So the XMLHttpRequest doesn't seem to work.
My code:
main.js:
var Widget = require("widget").Widget;
var tabs = require('tabs');
exports.main = function() {
var pageMod = require("page-mod");
var data = require("self").data;
scriptFiles = data.url("s.js");
pageMod.PageMod({
include: "*.facebook.com",
contentScriptWhen: 'ready',
contentScriptFile: scriptFiles
});
s.js
function addCSS(theTheme) {
var s = document.createElement('link');
s.type = 'text/css';
s.rel = 'stylesheet';
s.href = theTheme+'.css';
(document.head||document.documentElement).appendChild(s);
}
function getData() {
client = new XMLHttpRequest();
try{
client.open('GET','http://localhost:8888/istyla/login/popuplogin/myaccount.php');
} catch (e){
alert( "error while opening " + e.message );
}
client.onreadystatechange = function(){
if (client.readyState ==4){
user_data = client.responseText;
window.user_data = user_data;
var currenttheme = user_data;
window.currenttheme = currenttheme;
addCSS(currenttheme);
}
}
client.send(null);
}
getData();
P.S. The CSS file is in the data folder.
Im very new to this so not sure if I can help. Have you had a look in the error console(ctrl+shift+j) if its complaining about anything? You can console.log() and it will show in here.
Maybe use the Request lib instead of XMLHttpRequest
Here is a snippet from my code:
var Request = require("request").Request;
getUserDetails : function(userID, callback)
{
Request({
url: Proxy.remoteUrl,
content : {command:'getUser',UserID:userID},
onComplete: function(response) {callback(response.json)}
}).get();
}
Content scripts run with the privileges of the page that they are in. So if the page isn't allowed to load http://localhost/, your content script won't be able to do it either. You don't get an immediate error due to CORS but the request will fail nevertheless. What you need to do is to send a message to main.js so that it does the request (extension code is allowed to request any URI) and sends the data back to the content script.
As said, the content script has the same privileged of the web page where is attached, that is meaning you're under the Same Origin Policy.
You can solve the issue as suggested, so sent a message to the add-on code (that is not restricted by the SOP) and post the result back to the content script.
Here an example how the code could be: https://groups.google.com/d/topic/mozilla-labs-jetpack/VwkZxd_mA7c/discussion