Inherit just the javascript code from a master page - javascript

So I have a Javascript function on my master page. It works fine when I call it from pages that derive from this master page, however, on pages that don't, it obviously doesn't work. I am not able to put it in another .js file either because it uses some embedded c# code in it, so it has to be within a <script> tag.
This is the function:
function GridExport(viewUrl, fileName)
{
var actionUrl = "<%= System.Web.VirtualPathUtility.ToAbsolute("~/mvc/Indications.cfc/ExportToExcel")%>";
var guid = GetGUIDValue();
window.open((actionUrl + "?id=" + guid + "&viewName=" + viewUrl + "&fileName=" + fileName), null, null, null);
}
is there a way I can just include the Javascript definitions from my master page in another view without deriving from the master page?

You could create a UserControl containing this <script> or abstract out the actionUrl to a parameter of the GridExport function
function GridExport(viewUrl, fileName, actionUrl)
{
var guid = GetGUIDValue();
window.open((actionUrl + "?id=" + guid + "&viewName=" + viewUrl + "&fileName=" + fileName), null, null, null);
}
Another handy way to avoid this path problem would be to have a global variable to define the root of the site:
var root = "<%= System.Web.VirtualPathUtility.ToAbsolute("~/") %>";
then your function could always use this variable and append what it needs:
function GridExport(viewUrl, fileName)
{
var actionUrl = root + "mvc/Indications.cfc/ExportToExcel";
var guid = GetGUIDValue();
window.open((actionUrl + "?id=" + guid + "&viewName=" + viewUrl + "&fileName=" + fileName), null, null, null);
}

Master pages can be embedded within each other. Why not just make a master page with only your javascript in it. Then make another master page that has the javascript master page as it's master. When creating new pages you can choose which one to use.
MasterPage1 -> Just javascript
MasterPage2 -> Contains your other stuff and has MasterPage1 as it's master
If you just want the javascript then user MasterPage1, for everything else user MasterPage2.

Related

JSLink to Hyperlink Column in SharePoint List

I have an external list in SharePoint that includes a URL column. The URL column is a calculated field in SQL server, so the entire URL is already there. I need this field to hyperlink and I have been trying to use JSLink to do so. What would the JavaScript for that look like?
For example, if my fields were...
First Name | Last Name | Profile URL
How would I get the URL in the Profile URL field to hyperlink?
I have been looking for solutions all morning without any luck. I am not familiar with JavaScript, so the code I am using is pieced together from posts I have been reading. I have made sure the my JSLink address is correct.
~site/SiteAssets/myCode.js
I have tried different variations of code. My latest is this:
(function () {
var profUrlField = {};
profUrlField.Templates = {};
profUrlField.Templates.Fields = {
"Profile_X0020_URL": {
"View": function (ctx) {
var urlField = ctx.CurrentItem[ctx.CurrentFieldSchema["Profile_X0020_URL"]];
return "<a href='" + urlField + "'>" + urlField + "</a>";
}
}
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(profileUrlField);
})();
After applying my JSLink to my web part I reload the page and nothing happens. No errors but no links.
I'm also not sure how to reference the column. In SQL Server it is PROFILE_URL, but in the SharePoint list header it is Profile URL.
Modify the code as below to check if it works.
(function () {
var profUrlField = {};
profUrlField.Templates = {};
profUrlField.Templates.Fields = {
"PROFILE_URL": {
"View": function (ctx) {
var urlField = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];
return "<a href='" + urlField + "'>" + urlField + "</a>";
}
}
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(profileUrlField);
})();

Add params to URL if page gets reloaded

Heyho, I want to add GET params like?USER_NAME=Max&USER_ID=01 to the URL if the page gets reloaded. I already got a few snippets for changing the URL / adding params. But I need something to detect the page reload and execute a function. Or a way to change the path of the Url directly if the page gets reloaded.
I tried several things like beforeunload and navigation types.
$(window).bind('beforeunload', function() {
// EDIT: vars like uname etc are defined
var newurlgetstring = "?USER_NAME=" + uname + "&USER_EMAIL=" + uemail + "&LAST_NAME=" + lname + "&PRE_NAME=" + fname + "&UTITEL=" + utitel + "&U_ID_T=" + uidt + "&MV=" + mv + "&V=" + uv ;
var newurl = window.location.protocol + "//" + window.location.host +window.location.pathname + newurlgetstring;
window.history.pushState({path:newurl},'',newurl);
});
But I want able to execute a function with beforeunload. I was just able to display a return question.

Reuse javascript code on client side (node.js, express)

I'm still new to Node.js, but I'll try to explain my problem as good as I can.
So I'm working on a movie site to practice my node.js/express skills a bit and I use the following elements (img) on basically every page of my website:
Header with stats and search input and a navigation bar (will be reused on every page)
The follow JS-code are two examples of actions on the client side that I use to navigate to other web pages, this then activates GET on the client side.
$(function () {
$('button').click(function (event) {
event.preventDefault()
// the value people enter in the search box
var search = $('.searchInput').val();
//replace spaces with _
var res = search.replace(/\s/g, "_");
//build the URL
var link = window.location.protocol + '//' + window.location.host + '/search/' + res;
// redirect to trigger GET in indexjs with specific search value
window.location.replace(link);
});
$('.lists').click(function (event) {
var link = window.location.protocol + '//' + window.location.host + '/lists/topAll';
window.location.replace(link);
})
});
I want this to be the same code on every page. I could type the same code every time, but that would be a waste of time.For HTML and CSS I am able to use templates (HTML) or import other CSS files to save time. Is there something similar for JS on the client side?
Put that code in a file, for example "navigator.js" and then load it in your html header in every page you want to use it
navigator.js:
$(function () {
$('button').click(function (event) {
event.preventDefault()
// the value people enter in the search box
var search = $('.searchInput').val();
//replace spaces with _
var res = search.replace(/\s/g, "_");
//build the URL
var link = window.location.protocol + '//' + window.location.host + '/search/' + res;
// redirect to trigger GET in indexjs with specific search value
window.location.replace(link);
});
$('.lists').click(function (event) {
var link = window.location.protocol + '//' + window.location.host + '/lists/topAll';
window.location.replace(link);
})
});
index.html
<script src="navigator.js"></script>
Finally i suggest you to assign an id to your button, for example "searchButton" instead only "button"
Hope this helps

generating link using Url.Action with jquery href attr

I'm trying to generate a link using following
$(this).parent().attr('href', '#Url.Action("Create", "Home"' + '?clientId=' + clientId + '&clientName=' + clientName);
somewhere I read that I need to isolate this Url.Action with controller and action into variable so I tried with this
var a = '#Url.Action("Create", "Home"';
$(this).parent().attr('href', a + '?clientId=' + clientId + '&clientName=' + clientName);
But this still doesn't work.
In browser I'm getting
http://localhost:1328/Home/Index2/#Url.Action%28%22Create%22,%20%22Home%22?clientId=181&clientName=undefined
Another option is to store the url with data-* attributes and access them. In the View you can add the below attribute:
data-url='#Url.Action("Create", "Home")'
Now you can access this in the script with:
var base = $(this).data('url');
$(this).parent().attr('href', base + '?clientId='+ clientId +'&clientName=' + clientName);
Your script should be on Razor page in order to make #Url.Action helper work.
When you place it there this should work:
//this line should generate /Home/Create string
var urlNoParam = '#Url.Action("Create", "Home")';
//and here you just add params as you want
$(this).parent().attr('href', urlNoParam + '?clientId=' + clientId + '&clientName=' + clientName);

How to save the current webpage with casperjs/phantomjs?

Is there a way to save the current webpage by using casperjs or phantomjs?
I tried to get the html and save it into a file. But the resulting file was a lot different from the screenshot of that time (with casper.capture). Is there a way to save the current webpage?
Andrey Borisko suggested to use the disk cache to retrieve the resources. My solution is not that efficient, but you don't need to decompress text files.
I use XMLHttpRequest to retrieve all resources after I registered them with the resource.received event handler. I then filter the resources into images, css and fonts. The current limitation is that remote resource paths that contain something like ../ or ./ are not handled correctly.
I retrieve the current page content with getHTML and iterate over all captured resources to replace the path used in the markup, that is identified by a portion of the complete resource URL, with a randomly generated file name. The file extension is created from the content type of the resource. It is converted using mimeType from this gist.
Since CSS files may contain background images or fonts, they have to be processed before saving to disk. The provided loadResource function loads the resource, but does not save it.
Since XMLHttpRequest to download the resources the script has to be invoked with the --web-security=false flag:
casperjs script.js --web-security=false
script.js
var casper = require("casper").create();
var utils = require('utils');
var fs = require('fs');
var mimetype = require('./mimetype'); // URL provided below
var cssResources = [];
var imgResources = [];
var fontResources = [];
var resourceDirectory = "resources";
var debug = false;
fs.removeTree(resourceDirectory);
casper.on("remote.message", function(msg){
this.echo("remote.msg: " + msg);
});
casper.on("resource.error", function(resourceError){
this.echo("res.err: " + JSON.stringify(resourceError));
});
casper.on("page.error", function(pageError){
this.echo("page.err: " + JSON.stringify(pageError));
});
casper.on("downloaded.file", function(targetPath){
if (debug) this.echo("dl.file: " + targetPath);
});
casper.on("resource.received", function(resource){
// don't try to download data:* URI and only use stage == "end"
if (resource.url.indexOf("data:") != 0 && resource.stage == "end") {
if (resource.contentType == "text/css") {
cssResources.push({obj: resource, file: false});
}
if (resource.contentType.indexOf("image/") == 0) {
imgResources.push({obj: resource, file: false});
}
if (resource.contentType.indexOf("application/x-font-") == 0) {
fontResources.push({obj: resource, file: false});
}
}
});
// based on http://docs.casperjs.org/en/latest/modules/casper.html#download
casper.loadResource = function loadResource(url, method, data) {
"use strict";
this.checkStarted();
var cu = require('clientutils').create(utils.mergeObjects({}, this.options));
return cu.decode(this.base64encode(url, method, data));
};
function escapeRegExp(string) {
// from https://stackoverflow.com/a/1144788/1816580
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
function replaceAll(find, replace, str) {
// from https://stackoverflow.com/a/1144788/1816580
return str.replace(find, replace);
}
var wrapFunctions = [
function wrapQuot1(s){
return '"' + s + '"';
},
function wrapQuot2(s){
return "'" + s + "'";
},
function csswrap(s){
return '(' + s + ')';
}
];
function findAndReplace(doc, resources, resourcesReplacer) {
// change page on the fly
resources.forEach(function(resource){
var url = resource.obj.url;
// don't download again
if (!resource.file) {
// set random filename and download it **or** call further processing which in turn will load ans write to disk
resource.file = resourceDirectory+"/"+Math.random().toString(36).slice(2)+"."+mimetype.ext[resource.obj.contentType];
if (typeof resourcesReplacer != "function") {
if (debug) casper.echo("download resource (" + resource.obj.contentType + "): " + url + " to " + resource.file);
casper.download(url, resource.file, "GET");
} else {
resourcesReplacer(resource);
}
}
wrapFunctions.forEach(function(wrap){
// test the resource url (growing from the back) with a string in the document
var lastURL;
var lastRegExp;
var subURL;
// min length is 4 characters
for(var i = 0; i < url.length-5; i++) {
subURL = url.substring(i);
lastRegExp = new RegExp(escapeRegExp(wrap(subURL)), "g");
if (doc.match(lastRegExp)) {
lastURL = subURL;
break;
}
}
if (lastURL) {
if (debug) casper.echo("replace " + lastURL + " with " + resource.file);
doc = replaceAll(lastRegExp, wrap(resource.file), doc);
}
});
});
return doc;
}
function capturePage(){
// remove all <script> and <base> tags
this.evaluate(function(){
Array.prototype.forEach.call(document.querySelectorAll("script"), function(scr){
scr.parentNode.removeChild(scr);
});
Array.prototype.forEach.call(document.querySelectorAll("base"), function(scr){
scr.parentNode.removeChild(scr);
});
});
// TODO: remove all event handlers in html
var page = this.getHTML();
page = findAndReplace(page, imgResources);
page = findAndReplace(page, cssResources, function(cssResource){
var css = casper.loadResource(cssResource.obj.url, "GET");
css = findAndReplace(css, imgResources);
css = findAndReplace(css, fontResources);
fs.write(cssResource.file, css, "wb");
});
fs.write("page.html", page, "wb");
}
casper.start("http://www.themarysue.com/").wait(3000).then(capturePage).run(function(){
this.echo("DONE");
this.exit();
});
The magic happens in findAndReplace. capturePage is completely synchronous so it can be dropped anywhere without much head ache.
URL for mimetype.js
No, I don't think there is an easy way to do this as phantomjs doesn't support rendering pages in mht format (Render as a .mht file #10117). I believe that's what you wanted.
So, it needs some work to accomplish this. I did something similar, but i was doing it the other way around I had a rendered html code that I was rendering into image/pdf through phantomjs. I had to clean the file first and it worked fine for me.
So, what I think you need to do is:
strip all js calls, like script tags or onload attributes, etc..
if you have access from local to the resources like css, images and so on (and you don't need authentication to that domain where you grab the page) than you need to change relative paths of src attributes to absolute to load images/etc.
if you don't have access to the resources when you open the page then I think you need to implement similar script to download those resources at the time phantomjs loads the page and then redirect src attributes to that folder or maybe use data uri.
You might need to change links in css files as well.
This will bring up the images\fonts and styling you are missing currently.
I'm sure there are more points. I'll update the answer if you need more info, once I see my code.

Categories

Resources