Dashboard widget: getting version number from Info.plist - javascript

I'm writing a Dashboard widget in Dashcode, and on the back side, I've got a string for credits. I want to include the widget's version number in that string, but if possible, I want to programmatically grab it from the CFBundleVersion or CFBundleShortVersionString key in Info.plist to avoid having to change the number in multiple places if and when I update the widget.
Searches on Apple's developer documentation, Google and various forums have proven fruitless so far. What I'd like to know is whether there's a built-in way to do this that Apple included but forgot to mention (like var version = widget.version(); or something), or whether my script will have to pull in and parse the entire plist before plucking out the one value I actually want.
Thanks for any help you can provide!

I seem to have found the answer: use Dashcode's "data source" facility to read in Info.plist as an XML data source. From there, this blog post showed me how to traverse the plist's structure and get the correct string (in this case, the fifth <string> element in the file, corresponding to CFBundleShortVersionString.
The function I ended up with:
function getWidgetVersion() {
var dataSource = dashcode.getDataSource("infoPlist");
var version = dataSource.selection().valueForKey("dict").valueForKey("string")[4]; // This line and the previous could probably be combined for the sake of brevity
if (typeof(version) == 'string') {
document.getElementById("creditsLabel").innerHTML += version; //I'll change this to just pass the number on
}
}
Since the text of the creditsLabel div has already been started off with a localized string, I get a nice little label saying "Version 1.0".

Related

Remove last 3 letters of div (hidde also in browser page source)

this is my HTML
<div id="remove">Username</div>
and this is my JS code
function slice() {
var t = document.getElementById("remove");
t.textContent = t.textContent.slice(0, -3);
}
slice();
Username load from foreach
{foreach from=$last_user item=s}
{$s.date}
{$s.username}
{/foreach}
This code working and remove 3 letter but when right click on browser and look at page sources i can see "Username" !
I need remove three letter because of privacy and security .
something like
*** name or usern ***
Thank for help me !
The only secure way to make sure the client can't see a particular piece of information is to never send it to the client in the first place. Otherwise, there will always be a way for the client to examine the raw payloads of the network requests and figure out the information they aren't supposed to know.
You'll need to fix this on your backend - either hard-code in
<div id="remove">Usern</div>
or, for a more dynamic approach, use a template engine (or whatever's generating the HTML) and look up how to change strings with it. For example, in EJS, if user is an object with a username property, you could do
<div id="remove"><%= user.username.slice(0, -3) %></div>
Changing the content only with client-side JavaScript will not be sufficient, if you wish to keep some things truly private.
With Smarty, you can define a modifier that takes a string and returns all but the last three characters of it.
function smarty_modifier_truncate_three($string)
{
return substr($string, 0, -3);
}
and then in your template, replace
{$s.username}
with
{$s.username|truncate_three}
If you want only the first three characters, it's easier because you can use the built-in truncate.
{$s.username|truncate:3}
JS doesn't change the source, it can only change the DOM, so what you can do is to keep the element empty and add a value to it using js, but don't forget that js runs on the client's side so its better here to send the string from the server without the last 3 characters.

sharepoint Online/365 Jquery, Set Lookup Column Not working e.i ($("select[Title='Column']")

I've been doing some work on Sharepoint Online/365 and have got stuck trying to set the value of a lookup or choice column in NewForm.aspx
Narrowed my problem down to not being able to set lookup/Choice Columns
I have simplified a code on my page down to
//Phase being a Choice Column & Closure a case sensitive valid option
$("select[title='Phase']").val("Closure");
//ProjectName being a Lookup Column & Test2 a case sensitive valid entry in the list
$("select[title='ProjectName']").val("Test2");
I have no problem setting text fields as the following code works fine on a text field I created
$("input[title='TextField']").val("Test2");
I have used the following Jquery libraries 1.7.2/min.js and 1.11.3
Not sure whether you used _spBodyOnLoadFunctionNames.push() method for your logics. Usually you have to wait all SharePoint DOM objects are loaded and then to execute your jQuery code. If you used SharePoint JavaScript library, you probably needs to call ExecuteOrDelayUntilScriptLoaded() to make sure your call is called after curtain SharePoint .js files are loaded.
First Thanks "Verona Chen" and " DIEGO CARRASCAL" because of who i've learnt a few other tricks in SharePoint which will help with other projects.
My original script before the question was trying to use a query string to populate a field in newform.aspx (which i have done on sharepoint 2013 with code i have found here on)
Unforuntaly with sharepoint online/365 This code was no longer working.
This code has fixed my issue (though it does change how a few previous pages are constructed)
Appologies if this doesn't directly answer the above question (as this was me trying to breakdown the overall issue i was having into something simpler and easier to address based on me narrowing down the issue in my original code) however as I am now up and running, it seems only polite to post the outcome.
Prior to code, i have a projects list with a "ProjectName" field. I was sending the field name into a URL and querystring to get mylist/newform.aspx?ProjectName=Test2
I was then trying to pull that Test2 into the lookup field (liked to the project list) "ProjectName" in the list "MyList"
But even when loading the function for my old script with _spBodyOnLoadFunctionNames.push() it wasn't working.
After playing with this for a while and after some looking around i found this peice of code
<script type="text/javascript">
(function () {
var ctx = {};
ctx.Templates = {};
ctx.Templates.Fields = {
'ProjectName': {
'NewForm': renderTaskCategory
}
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ctx);
})();
function renderTaskCategory(ctx) {
//extract cat parameter from a query string
var GetProjID = GetUrlKeyValue('ProjID');
//set lookup field value
ctx.CurrentFieldValue = GetProjID;
//default template for rendering Lookup field control
return SPFieldLookup_Edit(ctx);
}
</script>
This means that i have to change my previous url builds to create mylist/newform.aspx?ProjID=2
This script then finds item ID 2 (which happens to be test2 in this case) and puts the title of item 2 in my lookup field ProjectName
Thanks again to those that helped earlier.
And apologies again if this doesn't directly answer the question i originally asked.

Reference management with HTML/CSS/Javascript (BibTeX style)

HTML+CSS+Javascript tools offer a great way to create beautiful presentations (e.g. reveal.js + MathJax). However, I usually need to add citations to my presentations, and I would like to do that in a systematic way (so the bibliography is organized and the references are well-formatted). This is something that get's handled quite easily in LaTeX through BibTeX.
The best solution I've found so far comes from a library called bibtex-js. It seems to do a good job on rendering BiBTeX files in HTML as a bibliography listing, which is partially what I want. However, I don't only need to render bibliography listings, but also, I need to refer to entries in that bibliography by some index, and get a uniformly formatted reference marker. Take, for example, how LaTeX usually handles this problem:
%In thebibliography.bib
#article{darwin1859origins,
title={On the origins of species by means of natural selection},
author={Darwin, Charles},
journal={London: Murray},
year={1859}
}
%In mydocument.tex
As \cite{darwin1859origins} sustains in his ground-breaking book...
The previous code would be rendered as something like "As Darwin(1859) sustains in his ground-breaking book". Moreover, the formatting in which the citation is rendered could also be customizable (e.g. "Darwin,1859", "(Darwing,1859)", "[DWN59]", "[1]", etc.).
So the question is, how do you handle a similar task on a HTML document?
Thank you all in advance!
Yes, there is an emacs extension called org-mode, which is text processing with a markdown like syntax.
This can export to reveal-js trough this: https://github.com/yjwen/org-reveal
Or in my case I use the spacemacs extension: https://github.com/syl20bnr/spacemacs/tree/master/layers/%2Bemacs/org#revealjs-support
So org mode is an intermediate format that compiles to whatever you want, ie reveal-js, html, or even latex.
This includes a reference management system: https://github.com/jkitchin/org-ref
I'm unhappy with this for reveal.js, if we use this with reveal.js we end up having all the citation being presented as the link (whatever we type after cite:) and the full format citations are grouped on whatever slide you place them (so if you have more than 3 you can't read it correctly, although I guess its in the HTML). What I want is either the numbers I get in latex or footnote based citations, because in case of slides footnotes work kind off good.
This will of course work for just HTML pages, however you probably want to have presentations like me. I was searching for a solution for this when I stumbled upon this unanswered question so I guess here is your answer.
I made a project, incidentally also called bibtex-js. Available on npm.
I made it because most BibTeX parsers out there take considerable shortcuts in parsing. This one aligns closely with the authoritative document on BibTeX, Tame the BeaST and so works pretty well in terms of references and parsing author names, which seems what you are after.
I would say, based on some bibliographic standard, roll your own inline citation function:
import {parseBibFile, normalizeFieldValue} from "bibtex";
// Parse bib file
const bibFile = parseBibFile(bibtexString); // insert the darwin1859origins example as a string
// Sanity check: print all ids of entries in the bibfile
console.log(Object.keys(bibFile.entries$));
// Get the entry we are after
const entry = bibFile.getEntry("darwin1859origins");
// Get the relevant fields
// normalizeFieldValue turns a BibTeX string into a Javascript string
const year = normalizeFieldValue(entry.getField("year"));
// get first author
// "author" is a special kind of BibTeX field
const author = entry.getField("author").authors$[0];
function inlineCite(author){
return "("
+ (author.firstNames
.concat(author.vons)
.concat(author.lastNames)
.concat(author.jrs)).join(" ")
+ "," + year
+ ")";
}
console.log(inlineCite(author)); // (Charles Darwin, 1859)
You can do something complicated with et al. if you have multiple authors.

Remove prefix with unknown characters in JavaScript

I have a web page that the title is changed from 'Pagename' to '(1) Pagename' when there is an update on the page. That number increments to 50 each time there is a new update and then is maxed out showing '(50+) Timeline'.
When logging page views, Google Analytics shows the '(n) Pagename', which I don't want. So I found out how to manually change to logged page title, _gaq.push(["_set", "title", 'new title']);.
So my question is, how do I most efficiently remove the (1-50)/(50+) prefix and just get 'Pagename'? Is regex best for this?
This is what I'm using based on the answer from Ross:
var window_title = window.title.replace(/^\(\d+\+?\)\s/, '');
_gaq.push(["_set", "title", window_title]);
Yes, RegEx can do that.
window.title.replace(/^\(\d+\+?\)\s/, '');
Of course it depends on what software your site is using as perhaps it would be possible to just output the page title without that prefix in the relevant part of the template. So echoing that directly into the Google Analytics tag. But I think the above javascript is probably the easier solution to implement.

Javascript: Hijack Copy?

I was just reading the Times online and I wanted to copy a bit of text from the article and IM it to a friend, but I noticed when I did so, it automatically appended the link back to the article in what I had copied.
This is not a feature of my IM client, so I assume this happened because of some javascript on Times website.
How would I accomplish this if I wanted to implement it on my site? Basically, I would have to hijack the copy operation and append the URL of the article to the end of the copied content, right? Thoughts?
Here's the article I was reading, for reference: http://www.time.com/time/health/article/0,8599,1914857,00.html
It's a breeze with jQuery (which your referenced site is using):
$("body").bind('copy', function(e) {
// The user is copying something
});
You can use the jQuery Search & Share Plugin which does this exact thing whenever somebody copies more than 40 chars from your site: http://www.latentmotion.com/search-and-share/
The site that you referenced is apparently using a service called Tynt Insight to accomplish this though.
They are using the free service Tynt. If you want to accomplish the same thing, just use the same service.
What browser are you using (and what version)?
In some newer browsers, the user is either asked if a website can access the clipboard, or its simply not allowed. In other browsers (IE 6, for example), it is allowed, and websites can easily read from and write to your copy clipboard.
Here is the code (IE only)
clipboardData.setData("Text", "I just put this in the clipboard using JavaScript");
The "Copy & Paste Hijacker" jQuery plugin does exactly what you want and seems better suited for your purposes than Tynt or Search & Share: http://plugins.jquery.com/project/copypaste
You can easily format the copied content, specify max or min characters, and easily include the title of the page or the URL in the copied content exactly where you want.
I recently noticed this on another website and wrote a blog post on how it works. The jQuery example doesn't seem to actually modify what the user copies and pastes, it just adds a new context menu.
In short:
var content = document.getElementById("content");
content.addEventListener("copy", oncopy);
function oncopy() {
var newEl = document.createElement("p");
document.body.appendChild(newEl);
newEl.innerHTML = "In your copy, messing with your text!";
var selection = document.getSelection();
var range = selection.getRangeAt(0);
selection.selectAllChildren(newEl);
setTimeout(function() {
newEl.parentNode.removeChild(newEl);
selection.removeAllRanges();
selection.addRange(range);
}, 0)
}
The setTimeout at the end is important as it doesn't seem to work if the last part is executed immediately.
This example replaces your selected text at the last minute with my chosen string. You can also grab the existing selection and append whatever you like to the end.

Categories

Resources