I've had help from StackOverflow to generate this JavaScript to use in a GreaseMonkey script, which replaces an image with an H1 tag, to use on an Oracle E-Business Suite system where the instance name is held in an H1 tag:
// current page
var url_loc = window.location.href;
if (url_loc.indexOf("http://this.site:0123") == 0) { var env_label = "LIVE";}
if (url_loc.indexOf("http://this.site:1234") == 0) { var env_label = "TEST1";}
if (url_loc.indexOf("http://this.site:2345") == 0) { var env_label = "TEST2";}
if (url_loc.indexOf("http://this.site:3456") == 0) { var env_label = "TEST3";}
if (url_loc.indexOf("http://this.site:4567") == 0) { var env_label = "TEST4";}
if (url_loc.indexOf("http://this.site:5678") == 0) { var env_label = "TEST5";}
var imgs=document.getElementsByTagName('img');
for(var i=imgs.length-1;i>=0;i--){
if(imgs[i].title == 'NEW_UNI_LOGO.png' || imgs[i].title == 'Oracle') {
var h1 = document.createElement('h1');
h1.innerHTML = env_label;
imgs[i].parentNode.insertBefore( h1, imgs[i] );
imgs[i].parentNode.removeChild(imgs[i]);
h1.style.color = "red";
}
}
It would be really useful to also update the Title tag on the page to start with the env_label value. I don't want to replace all of the content of the Title tag, so that e.g. if the Title is:
<title>Oracle Applications Home Page</title>
I'd like to change it to e.g. for the Live Site:
<title>LIVE: Oracle Applications Home Page</title>
Basically just append env_label to the start of whatever is held in the title tag.
Thanks
Try this..
document.title = "Oracle Applications Home Page";
Appending the label to the title..
document.title =env_label + ": Oracle Applications Home Page";
Did you even try something before asking to it ? I can't think about a more simple problem ...
document.title = env_label + ": " + document.title;
Related
I have the following tag in my view.jsp:
<liferay-ui:input-localized id="message" name="message" xml="" />
And I know that I can set a XML and have a default value on my input localized. My problem is that I want to change this attribute with javascript. I am listening for some changes and call the function "update()" to update my information:
function update(index) {
var localizedInput= document.getElementById('message');
localizedInput.value = 'myXMLString';
}
Changing the value is only updating the currently selected language input (with the whole XML String). The XML String is correct, but I am not sure on how to update the XML for the input with javascript.
Is this possible?
PS: I have posted this in the Liferay Dev forum to try and reach more people.
After a week of studying the case and some tests, I think that I found a workaround for this. Not sure if this is the correct approach, but it is working for me so I will post my current solution for future reference.
After inspecting the HTML, I noticed that the Liferay-UI:input-localized tag creates an input tag by default, and then one more input tag for each language, each time you select a new language. Knowing that I created some functions with Javascript to help me update the inputs created from my liferay-ui:input-localized. Here is the relevant code:
function updateAnnouncementInformation(index) {
var announcement = announcements[index];
// the announcement['message'] is a XML String
updateInputLocalized('message', announcement['message']);
}
function updateInputLocalized(input, message) {
var inputId = '<portlet:namespace/>' + input;
var xml = $.parseXML(message);
var inputCurrent = document.getElementById(inputId);
var selectedLanguage = getSelectedLanguage(inputId);
var inputPT = document.getElementById(inputId + '_pt_PT');
inputPT.value = $(xml).find("Title[language-id='pt_PT']").text();
var inputEN = document.getElementById(inputId + '_en_US');
if (inputEN !== null) inputEN.value = $(xml).find("Title[language-id='en_US']").text();
else waitForElement(inputId + '_en_US', inputCurrent, inputId, xml);
var inputLabel = getInputLabel(inputId);
if (selectedLanguage == 'pt-PT') inputLabel.innerHTML = '';
else inputLabel.innerHTML = inputPT.value;
if (selectedLanguage == 'pt-PT') inputCurrent.value = inputPT.value;
else if (inputEN !== null) inputCurrent.value = inputEN.value;
else waitForElement(inputId + '_en_US', inputCurrent, inputId, xml);
}
function getSelectedLanguage(inputId) {
var languageContainer = document.getElementById('<portlet:namespace/>' + inputId + 'Menu');
return languageContainer.getElementsByClassName('btn-section')[0].innerHTML;
}
function getInputLabel(inputId) {
var boundingBoxContainer = document.getElementById(inputId + 'BoundingBox').parentElement;
return boundingBoxContainer.getElementsByClassName('form-text')[0];
}
function waitForElement(elementId, inputCurrent, inputId, xml) {
window.setTimeout(function() {
var element = document.getElementById(elementId);
if (element) elementCreated(element, inputCurrent, inputId, xml);
else waitForElement(elementId, inputCurrent, inputId, xml);
}, 500);
}
function elementCreated(inputEN, inputCurrent, inputId, xml) {
inputEN.value = $(xml).find("Title[language-id='en_US']").text();
var selectedLanguage = getSelectedLanguage(inputId);
if (selectedLanguage == 'en-US') inputCurrent.value = inputEN.value;
}
With this I am able to update the liferay-ui:input-localized inputs according to a pre-built XML String. I hope that someone finds this useful and if you have anything to add, please let me know!
To change the text value of an element, you must change the value of the elements's text node.
Example -
xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue = "new content"
Suppose "books.xml" is loaded into xmlDoc
Get the first child node of the element
Change the node value to "new content"
I know we can detect a re-visitor using cookies. But, is there a way to detect using LocalStorage only?
This is what I have started with. I have a LocalStorage object called "ifVisited", whose value will change to "true" only when the user is visiting the 2nd time.
<html>
<body>
<!–– Some code ––>
</body>
<script>
localStorage.setItem('ifVisited', 'false');
var cat = localStorage.getItem("ifVisited");
<!-- **How do I detect if the user is re-visiting?** -->
if(visit == 1)
{message=" Visit #1!";
var cat = localStorage.getItem("ifVisited");
<!-----------------Do Nothing------------------>
}
if(visit == 2)
{
localStorage.setItem('ifVisited', 'true');
var cat = localStorage.getItem("ifVisited");
message=" 2nd Visit, Push Promo"
<!-----------------Push Promo------------------>
}
if(visit > 2)
{
message=" Visit #3!";
var cat = localStorage.getItem("ifVisited");
age.setItem('ifVisited', 'false');
<!-----------------Do Nothing------------------>
}
</script>
</html>
if (localStorage) {
var visits = localStorage.getItem('visits');
if (visits == null) visits = 1;
if (visits == 1) console.log("First visit")
else console.log(visits + ' times visited')
localStorage.setItem('visits', visits + 1);
}
visitor counter example below using localstorage
<html>
<body>
<div id="container"></div>
</body>
<script>
function displayCounter() {
// check if the localStorage object is supported by the browser
if ('localStorage' in window && window['localStorage'] !== null) {
// if the counter has been defined, increment its value, // otherwise, set it to 0
('counter' in localStorage && localStorage['counter'] !== null) ? localStorage['counter']++ : localStorage['counter'] = 0;
var container = document.getElementById('container');
if (!container) { return };
// display the counter on screen
container.innerHTML = 'Hey, you visited this page ' + localStorage['counter'] + ' times.';
}
}
// call the 'displayCounter()' function when the web page is loaded
window.onload = function () {
displayCounter();
}
</script>
</html>
I'm working on a site where users can paste in embed codes from the likes of twitter, youtube, instagram, facebook, etc. The Embed code is validated and saved if valid.
The users can then see and edit the code and this is where some code fails validation. E.g. Twitter embed codes may contain < (aka '<') in the post name/text. When pasting in the code originally it passes validation as it contains <, but when displaying the code back to the user the browser shows < in the textarea and this is then submitted if the user clicks save. Our validation function treats this as the start of a tag and the validation fails.
Possible solution 1:
Better validation. The validation we use now looks like this It basically finds the tags (by looking for '<' etc) and checks that each open tag has a closing tag. There must be a better/standard/commonly used way:
(function($) {
$.validateEmbedCode = function(code) {
//validating
var input = code;
var tags = [];
$.each(input.split('\n'), function (i, line) {
$.each(line.match(/<[^>]*[^/]>/g) || [], function (j, tag) {
var matches = tag.match(/<\/?([a-z0-9]+)/i);
if (matches) {
tags.push({tag: tag, name: matches[1], line: i+1, closing: tag[1] == '/'});
}
});
});
if (tags.length == 0) {
return true;
}
var openTags = [];
var error = false;
var indent = 0;
for (var i = 0; i < tags.length; i++) {
var tag = tags[i];
if (tag.closing) {
// This tag is a closing tag. Decide what to do accordingly.
var closingTag = tag;
if (isSelfClosingTag(closingTag.name)) {
continue;
}
if (openTags.length == 0) {
return false;
}
var openTag = openTags[openTags.length - 1];
if (closingTag.name != openTag.name) {
return false;
} else {
openTags.pop();
}
} else {
var openTag = tag;
if (isSelfClosingTag(openTag.name)) {
continue;
}
openTags.push(openTag);
}
}
if (openTags.length > 0) {
var openTag = openTags[openTags.length - 1];
return false;
}
return true
};
}
Possible solution 2:
Encode the text containing '<' (i.e. textLine.replace(/</g, '<')) without encoding tags like <blockquote class="...>.
I've been experimenting with something like:
$(widget.find("textarea[name='code']").val()).find('*')
.each(function(){
// validate $(this).text() here. Need to get text only line by
// line as some elements look like <p>some text <a ...>text
// </a>more text etc</p>
});
Possible solution 3:
Display < as < and not < in the browser/textarea. We use icanhaz for templating (much like moustache).
Using date.code = '<' with <textarea name="code">{{{code}}}</textarea> in the template does not work, neither does {{code}}.
So I played some more and the following works, but I am still interested in suggestions for better embed code validation or better answers.
After the edit form (inc textarea) code is created using the icanhaz template (i.e. after widget = ich.editEmbedWidgetTemplate(encoded_data);) I do the following to encode instances of < etc into < etc. ' has to be encoded manually using replace.
var embedCode = '';
$( widget.find("textarea[name='code']").val() )
.filter('*')
.each(function(){
embedCode += this.outerHTML.replace(/'/g, ''');
});
widget.find("textarea[name='code']").val(embedCode);
I have a sharepoint webpart I am printing using the script below.
The problem is I need to add a a picture to the header of the page it prints that is located at an address. I am trying to modify this but I don't have alot of javascript experience not sure what the syntax is.
Also I would like to specify the image to a specific size and center it is that possible?
I am aware the src is set to "url" I just don't want to share my actual link on here.
<center>
<input onclick="javascript:void(PrintWebPart())" type="button" value="Print Proof of Pricing"/>
</center>
<script language="JavaScript">
//Controls which Web Part or zone to print
var WebPartElementID = "ctl00_ctl34_g_db6615a7_4c3b_4a14_9bbc_43ce9d63c24d_FormControl0";
var d= new Date();
var elem = document.createElement("img");
elem.setAttribute("src", "url");
elem.setAttribute("height", "768");
elem.setAttribute("width", "1024");
elem.setAttribute("alt", "Tag");
elem.setAttribute("align", "middle");
//Function to print Web Part
function PrintWebPart()
{
var bolWebPartFound = false;
if (document.getElementById != null)
{
//Create html to print in new window
var PrintingHTML = '<HTML>\n<HEAD>\n';
//Take data from Head Tag
if (document.getElementsByTagName != null)
{
var HeadData= document.getElementsByTagName("HEAD");
if (HeadData.length > 0)
PrintingHTML += HeadData[0].innerHTML;
}
PrintingHTML += '\n</HEAD>\n<BODY>\n';
var WebPartData = document.getElementById(WebPartElementID);
if (WebPartData != null)
{
PrintingHTML +='<div id="imageDiv">\n</div>\n'
PrintingHTML += WebPartData.innerHTML;
PrintingHTML += "Pricing Date: " +d;
bolWebPartFound = true;
}
else
{
bolWebPartFound = false;
alert ('Cannot Find Web Part');
}
}
PrintingHTML += '\n</BODY>\n</HTML>';
//Open new window to print
if (bolWebPartFound)
{
var PrintingWindow = window.open("","View Proof of Pricing",
"toolbar,width=800,height=600,scrollbars,resizable,menubar");
PrintingWindow.document.open();
PrintingWindow.document.write(PrintingHTML);
PrintingWindow.document.getElementById("imageDiv").appendChild(elem);
// Open Print Window
}
}
</script>
I believe you can set the image as background to "imageDiv" as
document.getElementById("imageDiv").style["background"]="url(***YOUR_URL***) no-repeat center center";
Note: You do need to give a height to the container as per your need, say
document.getElementById("imageDiv").style["min-height"]="300px";
I'm not too good on the whole JavaScript (I can do some basic validations) but this isn't my zone
I've got a piece of code below that I'm trying to understand what it does, I can read any code and understand a few parts, but this just stumped me.
Here:
function tm_search_click() {
if (document.getElementById('tm').value == 'Enter your trademark') {
document.getElementById('tm').style.backgroundColor = '#fcc';
return false;
} else {
window.location = '?tm=' + escape(document.getElementById('tm').value);
return true;
}
}
function qs(a) {
a = a.replace(/[[]/, "\[").replace(/[]]/, "\]");
var b = "[\?&]" + a + "=([^&#]*)";
var c = new RegExp(b);
var d = c.exec(window.location.href);
return d == null ? "" : decodeURIComponent(d[1]).replace(/+/g, " ")
}
if (qs("tm") != "") {
tm_trademark = document.getElementById("tm").value = unescape(qs("tm"));
tm_partner = "migu2008";
tm_frame_width = 630;
tm_frame_height = "auto";
tm_trademark_country_code = "GB";
tm_css_url = "http://remarqueble.com/api/theme/search_corporate.css";
document.getElementById("tmLoading").style.display = "block";
tm_on_search_result = function () {
document.getElementById("tmLoading").style.display = "none";
document.getElementById("tmLoaded").style.display = "block"
}
} else {
tm_search_method = "none"
}
That is all of it without the <script> tags.
Could I also edit this code so that it searches are made based on what option the user inputs?
I think it works like this (assuming that this is in tags inside html page)
Page loads.
The script checks if URL has 'tm' parameter. If it has, then it sets bunch of tm_.. parameters and callback function. I don't know how they are used.
User clicks something that triggers the tm_search_click
Script sets new URL for the page and browser starts loading that
Goto step 1.