Change the href="favicon2.ico" in javascript when the querystring is changed - javascript

I have this code in silverlight application in the default.aspx :
<head id="Head1" runat="server">
<link id="link1" rel="shortcut icon" href="favicon1.ico" type="image/vnd.microsoft.icon" />
<title id="Title1" >hello</title>
I need to change the href="favicon2.ico" in JavaScript when the querystring is changed.
I tried to write this, but it's not working:
<script type="text/javascript">
if( Request.QueryString ("user"). Equals("true", StringComparison.OrdinalIgnoreCase)) {
document.title="hi user";
document.getElementById('link1').href = ('favicon2.ico');
}
</script>
</head>
</html>

Add JavaScript function
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Change your code as purely JavaScript (You are mixing C# and JavaScript)
if(getParameterByName("user").toLowerCase() == "true")
{
document.title="hi user";
var newImage = new Image();
newImage.src = 'favicon2.ico?_=' + new Date().getTime();
document.getElementById('link1').href = newImage.src;
}
Update:
if(getParameterByName("user").toLowerCase() == "true")
{
document.title="hi user";
changeFavicon('favicon2.ico');
}
function changeFavicon(src) {
var link = document.createElement('link'),
oldLink = document.getElementById('link1');
link.id = 'link1';
link.rel = 'shortcut icon';
link.href = src;
if (oldLink) {
document.getElementsByTagName('head')[0].removeChild(oldLink);
}
document.getElementsByTagName('head')[0].appendChild(link);
}

Try replacing this in your code
document.getElementById('link1').href = "favicon2.ico";

Related

How to create a screenshot of browser window and save it to another page

I would like to ask what is the logic behind capturing the screen of browser window.Can we open this screenshot image in popup where user have an option to save the screenshot.
Here is my code In this code the Problem is that my browser screen have image also it captures text but not capturing image I couldn't get where the problem is ? Here is my code
<html lang="en">
<head>
<title>Take Web Page Screenshot with HTML5 and JavaScript </title>
</head>
<body>
<div>
<div style="background-image:url('assets/images/act.png');height: 50px;width: 50px;"></div>
<div><a class="btn btn-success" href="javascript:void(0);" onclick="generate()">Generate
Screenshot ยป</a>
</div>
<div>fsaffsfasfasfasfasfasff</div>
</div>
<script type="text/javascript">
(function (exports) {
function urlsToAbsolute(nodeList) {
console.log(nodeList);
if (!nodeList.length) {
return [];
}
var attrName = 'href';
if (nodeList[0].__proto__ === HTMLImageElement.prototype || nodeList[0].__proto__===HTMLScriptElement.prototype) {
attrName = 'src';
}
nodeList = [].map.call(nodeList, function (el, i) {
var attr = el.getAttribute(attrName);
if (!attr) {
return;
}
var absURL = /^(https?|data):/i.test(attr);
console.log(absURL);
if (absURL) {
return el;
} else {
return el;
}
});
return nodeList;
}
function screenshotPage() {
urlsToAbsolute(document.images);
urlsToAbsolute(document.querySelectorAll("link[rel='stylesheet']"));
var screenshot = document.documentElement.cloneNode(true);
var b = document.createElement('base');
b.href = document.location.protocol + '//' + location.host;
var head = screenshot.querySelector('head');
head.insertBefore(b, head.firstChild);
screenshot.style.pointerEvents = 'none';
screenshot.style.overflow = 'hidden';
screenshot.style.webkitUserSelect = 'none';
screenshot.style.mozUserSelect = 'none';
screenshot.style.msUserSelect = 'none';
screenshot.style.oUserSelect = 'none';
screenshot.style.userSelect = 'none';
screenshot.dataset.scrollX = window.scrollX;
screenshot.dataset.scrollY = window.scrollY;
var script = document.createElement('script');
script.textContent = '(' + addOnPageLoad_.toString() + ')();';
screenshot.querySelector('body').appendChild(script);
var blob = new Blob([screenshot.outerHTML], {
type: 'text/html'
});
return blob;
}
function addOnPageLoad_() {
window.addEventListener('DOMContentLoaded', function (e) {
var scrollX = document.documentElement.dataset.scrollX || 0;
var scrollY = document.documentElement.dataset.scrollY || 0;
window.scrollTo(scrollX, scrollY);
});
}
function generate() {
window.URL = window.URL || window.webkitURL;
window.open(window.URL.createObjectURL(screenshotPage()));
}
exports.screenshotPage = screenshotPage;
exports.generate = generate;
})(window);
</script>
</body>
</html>

Disqus in Ionic APP

I am trying to implement disqus commments in my ionic app. I know I have to host it on the domain its setup for which I believe I have configured correctly. Any assistance will be welcomed
Here is the code in my app.js for the ionic app
$scope.showComments = function () {
$scope.currentView = "comments";
//loadComments(params["shortname"], params["url"], params["title"], params["identifier"]);
//
var disqus_title = "Venue 1";
var disqus_identifier = '/venue/' + $stateParams.id;
var disqus_url = 'liverpool.li/venue/' + $stateParams.id;
var url = "http://liverpool.li/app/disqus.html?";
$scope.url = url + "shortname=liverpoolli&url=" + encodeURIComponent(disqus_url) +
"&title=" + encodeURIComponent(disqus_title) + "&identifier=" + encodeURIComponent(disqus_identifier);
$scope.url = $sce.trustAsResourceUrl($scope.url);
};
$scope.$on("$destroy", function () {
if ($scope.lastScriptElm && $scope.lastScriptElm.parentNode) {
$scope.lastScriptElm.parentNode.removeChild($scope.lastScriptElm);
$scope.lastScriptElm = null;
}
});
And the page it points to (disqus.html) located on my domain
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
</head>
<body>
<div id="disqus_thread"></div>
<script type="text/javascript">
var params;
var disqus_url;
var disqus_title;
var disqus_shortname;
var disqus_identifier;
window.onload = function () {
var match,
pattern = /\+/g,
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pattern, " ")); },
query = window.location.search.substring(1);
params = {};
while (match = search.exec(query))
params[decode(match[1])] = decode(match[2]);
if (params["shortname"] === undefined || params["url"] === undefined || params["title"] === undefined) {
alert("Required arguments missing");
}
else {
loadComments(params["shortname"], params["url"], params["title"], params["identifier"]);
}
};
function loadComments(shortname, url, title, identifier) {
disqus_url = url;
disqus_title = title;
disqus_shortname = shortname;
if (identifier !== undefined)
disqus_identifier = identifier;
else
disqus_identifier = "";
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = false;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
}
</script>
<noscript>Please enable JavaScript to view the comments powered by Disqus.</noscript>
blog comments powered by <span class="logo-disqus">Disqus</span>
</body>
</html>
I get the following error
we were unable to load disqus. if you are a moderator please see our
troubleshooting guide.
It looks like you're almost there. The only issue I see is the disqus_url variable must also include the protocol to be valid. Try using this line instead:
var disqus_url = 'http://liverpool.li/venue/' + $stateParams.id;

HTML video player

I want to play video file from local disk in browser so I found this code. Can You tell me why it does not work? On jsfiddle it works but when i copy it into project it won't work. Also can You tell me what gives function declaration like function name(x){variables}(window).
The error I get is Uncaught TypeError: Cannot read property 'addEventListener' of null
Thanks for Your help :)
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
(function localFileVideoPlayerInit(win) {
var URL = win.URL || win.webkitURL,
playSelectedFile = function playSelectedFileInit(event) {
var file = this.files[0];
var type = file.type;
var videoNode = document.querySelector('video');
var canPlay = videoNode.canPlayType(type);
canPlay = (canPlay === '' ? 'no' : canPlay);
var message = 'Can play type "' + type + '": ' + canPlay;
var isError = canPlay === 'no';
displayMessage(message, isError);
if (isError) {
return;
}
var fileURL = URL.createObjectURL(file);
videoNode.src = fileURL;
},
inputNode = document.querySelector('input');
if (!URL) {
displayMessage('Your browser is not ' +
'supported!', true);
return;
}
inputNode.addEventListener('change', playSelectedFile, false);
}(window));
</script>
<h1>HTML5 local video file player example</h1>
<div id="message"></div>
<input type="file" accept="video/*"/>
<video controls autoplay></video>
</body>
</html>
The problem is, your code is running before the DOM is ready/loaded.
There's two way to fix this.
1) Move the the entire javascript code block below <video controls autoplay></video>
or
2) Use document.addEventListener("DOMContentLoaded", function() { }); like this:
<script>
document.addEventListener("DOMContentLoaded", function() {
var URL = window.URL || window.webkitURL,
playSelectedFile = function playSelectedFileInit(event) {
var file = this.files[0];
var type = file.type;
var videoNode = document.querySelector('video');
var canPlay = videoNode.canPlayType(type);
canPlay = (canPlay === '' ? 'no' : canPlay);
var message = 'Can play type "' + type + '": ' + canPlay;
var isError = canPlay === 'no';
displayMessage(message, isError);
if (isError) {
return;
}
var fileURL = URL.createObjectURL(file);
videoNode.src = fileURL;
},
inputNode = document.querySelector(("input[type=file]"));
if (!URL) {
displayMessage('Your browser is not ' +
'supported!', true);
return;
}
inputNode.addEventListener('change', playSelectedFile, false);
});
</script>

Search facebook pages using javascript

I have an HTML application to search Facebook pages using pure JavaScript, no other libraries and no back-end.Most of the APIs that deal with searching and reading "pages" do not require user authorization, and they support JSONP (through the "callback" parameter).
My HTML code, index.html
<!doctype html>
<head>
<title>FaceBook Page Search API</title>
<script type="text/javascript" src='js/app.js'></script>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="container">
<div class="form-search">
<h3>Search FaceBook Pages</h3>
<p class="form-search-row"><input id="searchPages" type="text" placeholder="Enter name">
<button class="btn btn-medium btn-success" onclick="getData()" type="submit">Search</button>
</p>
</div>
</div>
<div class="offset1 pull-center page-results">
</div>
</body>
</html>
and app.js,
var getData = function(){
var my_JSON_object = {};
var http_request = new XMLHttpRequest();
var str, queryInput = document.getElementById("searchPages");
var searchFormRow = document.getElementsByClassName('form-search-row')[0];
var image=document.createElement('img');
if(!queryInput.value){
return;
}
str = encodeURIComponent(queryInput.value);
image.setAttribute('src', 'img/ajax-loader.gif');
image.setAttribute('width', '30px');
searchFormRow.appendChild(image);
var url = "https://graph.facebook.com/search?type=page&q="+ str;
http_request.open("GET", url, true);
http_request.onreadystatechange = function () {
var done = 4, ok = 200;
if (http_request.readyState == done && http_request.status == ok) {
my_JSON_object = JSON.parse(http_request.responseText);
displayResults(my_JSON_object);
image.parentNode.removeChild(image);
}
};
http_request.send(null);
};
var displayResults = function(pages){
var resultDiv = document.getElementsByClassName('page-results')[0];
if(pages.data.length){
resultDiv.innerHTML = "";
}
else{
resultDiv.innerHTML = "No results found";
}
for(var i=0; i<pages.data.length; i++)
{
var name = pages.data[i].name, category = pages.data[i].category, id= pages.data[i].id;
var page = document.createElement("div");
var pname = document.createElement("p");
var findmore = document.createElement("a");
var pcategory = document.createElement("p");
pname.innerHTML = name;
findmore.innerHTML = " find out more";
findmore.href= "detail.html?id="+id;
findmore.target = "_blank";
pname.appendChild(findmore);
pcategory.innerHTML = "Category: " + category;
pcategory.setAttribute('class',"small-font");
page.setAttribute('class','span2 pageDiv');
page.appendChild(pname);
page.appendChild(pcategory);
resultDiv.appendChild(page);
console.log(pages.data[i].name);
}
};
var getPageDeatil = function(){
var query = window.location.search.substring(1);
var vars = query.split("=");
getDetailsAjax(vars[1]);
};
var getDetailsAjax = function(pageId){
var my_JSON_object = {};
var http_request = new XMLHttpRequest();
var str = encodeURIComponent(pageId);
var url = "https://graph.facebook.com/"+ str;
http_request.open("GET", url, true);
http_request.onreadystatechange = function () {
var done = 4, ok = 200;
if (http_request.readyState == done && http_request.status == ok) {
my_JSON_object = JSON.parse(http_request.responseText);
displayDetailsResult(my_JSON_object);
}
};
http_request.send(null);
};
var displayDetailsResult = function(detail){
var resultDiv = document.getElementById('details');
var displayImage;
for (key in detail) {
if (detail.hasOwnProperty(key)) {
if(key=="cover"){
displayImage =true;
}
else{
var li = document.createElement("li");
li.setAttribute('class',"removeDecor");
li.innerHTML = key+ " : " + detail[key];
resultDiv.appendChild(li);
}
}
}
if(displayImage){
var heading = document.getElementById('header');
var image = document.createElement('img');
image.setAttribute('src', detail.cover.source);
heading.insertBefore(image);
}
};
Finally, the detail.html
<!doctype html>
<head>
<title>FaceBook Page Search API - Detail Page</title>
<script type="text/javascript" src='js/app.js'></script>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body onload="getPageDeatil()">
<div class="container">
<h3 id="header">More about Page</h3>
<div class="well">
<ul id="details">
</ul>
</div>
</div>
</body>
</html>
But it gives the following error in console.
{
"error": {
"message": "(#200) Must have a valid access_token to access this endpoint",
"type": "OAuthException",
"code": 200
}
}
Page search API do not require authorization right ? Then how can I solve this ?
Thanks for all, finally solved my problem by referring Facebook Developer Documentation.
First, got details about access_token here, https://developers.facebook.com/docs/reference/api/search/#access_tokens
Searches across page and place objects requires an app access token.
Each application should be registered in https://developers.facebook.com/apps to get an app_id and secret_id.
After getting this details,
Generate access_token using this URL https://graph.facebook.com/oauth/access_token?client_id=app_id&client_secret=secret_id&grant_type=client_credentials
The app_id and secret_id should be changed with generated one.
And changed my request URL in app.js file like this,
var access_token = ""; // my access token here
var url = "https://graph.facebook.com/search?type=page&q="+ str +"&access_token="+access_token;

How to create embed code for other sites

I have a service of job portal which other users can use for their sites and blogs. they copy embed code from my site, paste it in their site and display job board in their webpage. how create this embed code anyone can help me.
Here is example monster.com publisher website.
click Get sample code button.
<div id="MonsterJobSearchResultPlaceHolderIy8AAA_e_e" class="xmns_distroph"></div>
<script type="text/javascript">
(function() {
var oScript = document.createElement('script');
oScript.type = 'text/javascript';
oScript.async = true;
oScript.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'publisher.monster.com/Services/WidgetHandler.ashx?WidgetID=EAAQgDMlA5vzabXFzuv86ZpLpA--&Verb=Initialize';
var oParent = document.getElementsByTagName('script')[0];
oParent.parentNode.insertBefore(oScript, oParent);
})();
</script>
<a id="monsterBrowseLinkIy8AAA_e_e" class="monsterBrowseLink fnt4" href="http://jobsearch.monster.com/browse/">View More Job Search Results</a>
there are many ways to reach your goal. As you didn't explain your need explicitly, I just provide a simple example:
<script type='text/javascript' charset='utf-8'>
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
iframe.src = 'URL OF CONTENT YOU WANT TO PROVIDE';
iframe.width = 'THE WIDTH YOU WANT';
iframe.height = 'THE HEIGHT YOU WANT';
</script>
modify the code according to your need
escape this code in your html
have fun with your awesome embedded widget!
How To Create Embed With Javascript in .cs
Note: localhost:3197/website/js/embed/form.js'; // give your js path
FormBuilder(921,'MjEzNjkxMjU='); in this method first parameter give your form height and second your form name or Id. there Id is encoded format
StringBuilder sb = new StringBuilder();
sb.Append("<script type='text/javascript'>");
sb.Append("(function(d, t) { var s = d.createElement(t), options = {");
sb.Append("'async':true };");
sb.Append("s.src = ('https:' == d.location.protocol ? 'https://' : 'http://') + 'localhost:3197/website/js/embed/form.js';");
sb.Append("s.onload = s.onreadystatechange = function() {");
sb.Append("var rs = this.readyState; if (rs) if (rs != 'complete') if (rs != 'loaded') return;");
sb.Append("try { frm = new FormBuilder("+Form Height+",'"+FormId+"');frm.initialize(options);frm.display(); }");
sb.Append("catch (e) {}};");
sb.Append("var scr = d.getElementsByTagName(t)[0], par = scr.parentNode; par.insertBefore(s, scr);");
sb.Append("})(document, 'script');</script>");
txtjavascript.Value = sb.ToString(); // text box name
After Create embed script Simple and Easy Way Paste this script where you want to show in other page after that
(function(d, t) { var s =
d.createElement(t), options = {'async':true }; s.src = ('https:' ==
d.location.protocol ? 'https://' : 'http://') +
'localhost:3197/website/js/embed/form.js'; s.onload =
s.onreadystatechange = function() {var rs = this.readyState; if (rs)
if (rs != 'complete') if (rs != 'loaded') return; try { frm = new
FormBuilder(921,'MjEzNjkxMjU='); frm.initialize(options);
frm.display(); }catch (e) {}}; var scr =
d.getElementsByTagName(t)[0], par = scr.parentNode;
par.insertBefore(s, scr);})(document, 'script');
After That in your js file Create fuction like this and create iFrame ans create querystring where you fetch the form from database.
function FormBuilder(fHeight, formid) {
var iframe = document.createElement('iframe');
iframe.style = "height:" + fHeight + "px; width:100%; border:none";
iframe.setAttribute('allowTransparency', true);
iframe.frameBorder = "0";
iframe.scrolling = "no";
iframe.src = "http://localhost:3197/form/show-form?id="+ formid;
document.body.appendChild(iframe);
}

Categories