I have the following signal r client code on my razor partial view
It is working fine in partial view. I want to move it to an external javascript file.
<script type="text/javascript">
$(function () {
debugger;
$.connection.hub.logging = true;
var proxy = $.connection.broadcastMessage;
proxy.client.receiveNotification = function (message, count) {
debugger;
$("#not_count").html(count);
$("#not_count").show();
};
$.connection.hub.start();
});
</script>
How can i move this to an external JS file?
Add new javascript file(eg. signalrStuff.js) to solution with your code:
$(function () { debugger; $.connection.hub.logging = true; var proxy = $.connection.broadcastMessage;
proxy.client.receiveNotification = function (message, count) {
debugger;
$("#not_count").html(count);
$("#not_count").show();
};
$.connection.hub.start();
});
Then reference the new script replacing the javascript in the partial view:
<script src="signalrStuff.js" type="text/javascript"></script>
Make sure to load the jQuery script first.
Related
I have some simple code like this:
JS:
function load (element, url) {
element.innerHTML = '';
fetch(url).then(function (resp) {
return resp.text();
}).then(function (content) {
element.insertAdjacentHTML('afterbegin', content);
});
}
Content of url parameter of load function:
<div>
<button id="some-button">Execute click!</button>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('some-button').addEventListener('click', function () {
alert('Click at button has been executed.');
});
});
</script>
My question is: Why click event (or any other JS code) does not work? HTML content is loaded, script tag also do, but JS code does not executing. I just want to replace jQuery function load with custom function load described above.
Thanks in advance!
I think JS code included like that does not get recognized as JS code. I mean, text containing <script> tag is not considered as JS code and not run. Tried the following and it seems to work. Not sure if this solves your requirement, but it might help you understand the issue. Note the usage of document.createElement('script')
<div id="content"></div>
<script>
var scr = `document.getElementById('some-button').addEventListener('click', function () {
alert('Click at button has been executed.');
});`;
var content = `<div><button id="some-button">Execute click!</button></div>`;
document.getElementById('content').insertAdjacentHTML('afterbegin', content);
var sel = document.createElement('script');
sel.text = scr;
document.getElementById('content').appendChild(sel);
</script>
Here is final working code:
fetch(url).then(function (resp) {
return resp.text();
}).then(function (body) {
element.insertAdjacentHTML('afterbegin', body);
let scripts = element.getElementsByTagName('script');
for (let scr of scripts) {
var scriptContent = scr.innerText;
var newScript = document.createElement('script');
newScript.text = scriptContent;
scr.remove();
element.appendChild(newScript);
}
});
I have a cross platform app built using PhoneGap/Cordova.
I am trying to implement a function that runs an external JavaScript file when a controller loads. I am following a solution from HERE. And similarly HERE. But I want the JavaScript to execute without the window.open event, i.e. I want to run executeScript as soon as the device is ready.
How do I call the executeScript() without defining the var ref first though?
var navigation = angular.module("navigation", []);
navigation.controller("Navigation", function ($scope) {
var init = function () {
document.addEventListener("deviceready", onDeviceReady, false);
};
init();
function onDeviceReady() {
// LOAD EXTERNAL SCRIPT
var ref = window.open('http://www.haruair.com/', '_blank', 'location=yes, toolbar=yes, EnableViewPortScale=yes');
ref.addEventListener("loadstop", function () {
ref.executeScript(
{ file: 'http://haruair.com/externaljavascriptfile.js' },
function () {
ref.executeScript(
{ code: 'getSomething()' },
function (values) {
var data = values[0];
alert("Name: " + data.name + "\nAge: " + data.age);
});
}
);
});
});
You could try to add the script in the index.html file and do whatever you want from JS. Also, you must add to your whitelist this endpoint.
<!-- index.html -->
<script>
function onCustomLoad() {
//do stuff
}
</script>
<script src="your-custom-script" onload="onCustomLoad"></script>
you could use
var script = document.createElement("script");
script.type = "text/javascript";
script.id = "some_id";
script.src = 'http://haruair.com/externaljavascriptfile.js';
document.head.appendChild(script);
then call the function once finished
I have created a Single Page App, and this is my first one so maybe I'm on the wrong path.
I am using master-page in which I'm loading two other pages. Also, I'm using javascript modules so that I can use private variables and functions.
In the master-page, or Mail.html, I start the signalr connection, and I initialize the modules.
In the inbox sub-page I'm waiting "mail" from the server, and in the outbox I'm displaying all sent messages. In order to accomplish this I'm using two different modules (Inbox and Outbox).
My issue occurs when I load the second page (in this example Outbox) after inbox.html is loaded, in this scenario
signalr still works which is strange because that connection is used just in the Inbox page, in that module.
I've tried many things to prevent this, like unloading the current page before loading the next one, and I've also tried removing the scripts, starting a connection just in the inbox page, but nothing helps.
Also, I can't find where exactly is this function stored in the DOM when Outbox.html is loaded.
Here is my code:
Mail.html
<html>
<head>
//scripts
//css
</head>
<body>
<div class="page" id="Inbox">Inbox</div>
<div class="page" id="Outbox">Outbox</div>
<div id="loadPage">
</div>
<script type="text/javascript">
var SignalRHub = $.connection.hubs;
$.connection.hub.start();
var MailModule = {};
$('body').off('click', '.page').on('click', '.page', function () {
MailModule = {};
if ($(this).attr('id') == 'Inbox') {
$("#loadPage").empty().load("/Home/Inbox", function () {
MailModule.Inbox.Init();
});
}
if ($(this).attr('id') == 'Outbox') {
$("#loadPage").empty().load("/Home/Outbox", function () {
MailModule.Outbox.Init();
});
}
});
</script>
<body>
</html>
Inbox.html
<div id="items"></div>
<script>
(function (mail, $) {
mail.Inbox = (function () {
var ReceiveMail = function () {
// This is still active when there is new 'mail' from server
// even though I'm not on this page
SignalRHub.client.receiveMail = function (UserName, Title){
$("#items").append("<p>"+UserName+"-"+Title+"</p>");
}
};
var init = function () {
ReceiveMail();
};
return {
Init: init
};
}());
}(window.MailModule = window.MailModule || {}, jQuery));
</script>
Outbox.html
<div id="items"></div>
<script>
(function (mail, $) {
mail.Outbox = (function () {
var GetSend = function () {
$.get("URL", { UserId: UserId }, function (result) {
$("#items").append("<p>"+result[0].UserName+"-"+result[0].Title+"</p>");
}
};
var init = function () {
GetSend();
};
return {
Init: init
};
}());
}(window.MailModule = window.MailModule || {}, jQuery));
</script>
Note: Maybe this pattern is not right, and I'll be grateful if you give me a lead on how I can accomplish a better one
From below code I am trying to load javascript file TestJScript.js dynamically and after loading want to call javascript function LoadData() exist in that file. But I am getting error please check image.
Note: Error get only on IE-8.0.6001 update 0.
Please suggest me correction such that It will work from 6 to all version of IE.
Or any another solution.
if it require any windows updates. Please let me know.
Please don't suggest with JQUERY code
Javascript file code :
function LoadData() {
alert('ok');
}
Code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
function LoadJSFile() {
var js = document.createElement("script")
js.setAttribute("type", "text/javascript")
js.setAttribute("src", "C:\\TestJScript.js")
document.getElementsByTagName("head")[0].appendChild(js)
//call below function exist in TestJScript.js file
LoadData();
}
</script>
</head>
<body onload="LoadJSFile();">
</body>
</html>
Error Image:
Try this http://dustindiaz.com/scriptjs.
Like this:
$script('yui-base.js', function() {
// do stuff with base...
$script(['yui-anim.js', 'yui-connect.js'], function() {
// do stuff with anim and connect...
});
$script('yui-drag.js', function() {
// do stuff with drag...
});
});
The error reports a problem in the javascript file that you're loading. So the problem lies not in how you dynamically load the javascript file, but in the javascript file itself.
It looks like there is a problem with the file once it has loaded. Are you sure there is no syntax error in the file itself.
Also, I would recommend you use a relative path to the javascript file instead of the absolute path.
EDIT:
Try this:
function LoadJSFile() {
var script = document.createElement('script');
script.src = "C:\\TestJScript.js";
script.onload = function () {
LoadData();
};
document.getElementsByTagName("head")[0].appendChild(script)
}
You could try the following:
<script>
function LoadJSFile(src, callback) {
var js = document.createElement('script');
js.src = src;
js.async = true;
js.onreadystatechange = js.onload = function() {
var state = js.readyState;
if (!callback.done && (!state || /loaded|complete/.test(state))) {
callback.done = true;
callback();
}
};
document.getElementsByTagName('head')[0].appendChild(js);
}
LoadJSFile('C:\\TestJScript.js', function() {
LoadData();
});
</script>
If you are using c# code then another solution to solve this script error is, invoke script through c# code.
Code:
/
/Assiging html value to control
webBrowser.DocumentText = "HTML content";
//Calling document load completed event
webBrowser.DocumentCompleted += webBrowser_DocumentCompleted;
void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
HtmlDocument htmlDocument = webBrowser.Document;
HtmlElement htmlElementHead = htmlDocument.GetElementsByTagName("head")[0];
HtmlElement HtmlElementScript = htmlDocument.CreateElement("script");
HtmlElementScript.SetAttribute("text", "C:\\TestJScript.js");
htmlElementHead.AppendChild(HtmlElementScript);
htmlDocument.InvokeScript("LoadData");
webBrowser.DocumentCompleted -= webBrowser_DocumentCompleted;
}
I'm trying to make some small changes to an existing vb.net website that was written by someone who no longer works for the company, but every time a javascript function is called from a script file other than the one it's defined in, I see "Uncaught Reference Error: undefined is not a function" in Chrome's console.
Some of the scripts are being loaded in the master file:
<script type="text/javascript" src="Scripts/jquery-1.8.3.min.js"></script>
<script type='text/javascript' src="Scripts/JSExtensions.js"></script>
<script type='text/javascript' src="Scripts/GlobalUtilityFunctions.js"></script>
<script language="javascript" type="text/javascript">
jQuery.event.add(window, "load", resizeFrame);
jQuery.event.add(window, "resize", resizeFrame);
function resizeFrame() {
}
</script>
And the rest are loaded in the page itself:
<script type='text/javascript' src="Scripts/GridCalcFunctions.js"></script>
<script type='text/javascript' src="Scripts/InputEventHandlers.js"></script>
<script type='text/javascript' src="Scripts/FocusHandlers.js"></script>
<script type='text/javascript' src="Scripts/ProjectPageFunctions.js"></script>
<script type="text/javascript">
$(document).ready(function () {
});
$(window).unload(function () {
SaveOnExit();
});
function setPIDNumberLabel(ctlID, strVal) {
var val = strVal;
var ctl = top.$get(ctlID);
if (ctl != null) {
ctl.innerHTML = val;
}
}
</script>
GlobalUtilitesFunctions has no trouble accessing JSExtensions on other pages, but does here even though both are loaded in the master. I thought that must mean that the problem is caused by one of the files loaded on this page, but commenting them all out doesn't fix the issue.
As a specific example, GlobalUtilitiesFunctions contains this:
function GetAttributeSelector(attName, attValue, attOperator,attNot) {
attOperator = String.deNullValue(attOperator, "=");
[more code]
}
And I get an error that String.deNullValue is undefined, but over in JSExtenstions is:
String.iifValueIsNullOrEmpty = function (val, trueVal,falseVal) {
falseVal = String.getArgValue(falseVal, val);
if (String.isNullOrEmpty(val)) {
return trueVal;
}
else {
return falseVal;
}
}
String.deNullValue = function (val,defaultVal) {
var ret = "";
defaultVal = String.iifValueIsNullOrEmpty(defaultVal,"");
ret = String.iifValueIsNullOrEmpty(val,defaultVal);
return ret;
}
I've also tried running the site on a server (instead of inside Visual Studio) without solving the problem. Does anyone have an idea what might be causing this?
Here you can see this:
"A variable declared (using var) within a JavaScript function becomes LOCAL to the function.
The variable gets a local scope: It can only be accessed from within that function."
try to define functions like
function deNullValue(val,defaultVal) {
var ret = "";
defaultVal = String.iifValueIsNullOrEmpty(defaultVal,"");
ret = String.iifValueIsNullOrEmpty(val,defaultVal);
return ret;
}