Javascript bookmarklet to send url of current page to bing - javascript

A bookmarklet is a bookmark whose address is JavaScript code.
I would like to get the URL of the current page I am on and paste that into the text box of the Bing search page.
I can get the URL easily enough:
javascript:(function(){var%20url=window.location.href;alert(url);})();
But then how do I set the text box on the Bing page to my variable, url and then make it search?
This does not work:
javascript:(function(){var%20url=window.location.href;window.open%20("https://www.bing.com/search?q=&url");})();

Use the following bookmarklet code:
javascript:{window.location='http://bing.com/search?q='+encodeURIComponent(window.location.href)}

Of course you can do the way you have seen above. However, I have been in this situation where I wanted to control what to show from within my application.
Then I decided to connect my application from Bing API. The benefit is that it is free and you will not take user away from your website.
You will need to get the API Key from the Azure Market Place
Here is the code that you might want to give it a try , may be, in the future.
<html>
<head>
<title>BING API Integration</title>
<SCRIPT type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#searchButton').click(function(e){
$("#results").empty();
var query=$('#searchTerm').val();
if ( query) {
serviceOp = "Web";
search(query, serviceOp);
}
});
});
function search(query, serviceOp){
// your account key that youw ill get from https://datamarket.azure.com
var acctKey = '<Your Key>';
var rootUri = 'https://api.datamarket.azure.com/Bing/Search';
var requestUri = rootUri + "/" + serviceOp + "?$format=json&Query='" + query + "'";
$.ajax({
type: "GET",
url: requestUri,
headers: {
"Authorization": "Basic " + window.btoa(acctKey + ":" + acctKey)
},
}).done(function(o){
if ( o.d !== undefined){
var items = o.d.results;
for(var idx=0, len= items.length; idx < len; idx++ ){
var item = items[idx];
switch(item.__metadata.type){
case 'WebResult':
showWebResult(item);
}
}
}
});
}
// Shows one item of Web result.
function showWebResult(item) {
var p = document.createElement('p');
var a = document.createElement('a');
a.href = item.Url;
$(a).append(item.Title);
$(p).append(item.Description);
$('#results').append(a, p);
}
</script>
</head>
<body>
<label for="searchTerm">Search: </label>
<input id="searchTerm" type="text"/>
<button id="searchButton">Search</button>
<div id="results">
</div>
</body>
</html>

Related

JavaScript function being blocked by office addin

I have an outlook add-in that I have created. In this add-in I am trying to make a button pull some data from a website using APIs.
I was able to do this on with a local test but when I put the code into my add-in nothing happens. It gives an error in the console that says Tracking Prevention blocked access to storage for https://appsforoffice.microsoft.com/lib/1/hosted/en-us/outlook_strings.js. but when I commented out my javascript code, that error still came up. So I don't know why my code is being blocked.
Picture of problem:
On my local computer it works no problem:
Here is my code:
javascript:
function freshdesktickets() {
Office.onReady((info) => {
// window.parent.location.reload()
const url = "https://alloysystems.freshdesk.com/api/v2/tickets";
fetch(url, {
method: "GET",
withCredentials: true,
headers: {
// needed to base64 encode my key with ":x" at the end of the api key then I used that for the authorization header.
"authorization": "Basic YOUWILLNEVERGETMYAPIKEYLOL"
}
})
.then(resp => resp.json())
.then(data => {let text = "";
const output = document.querySelector('span.ms-font-m');
for (let i = 0; i < data.length; i++) {
let text = "Subject: " + JSON.stringify(data[i].subject) + "<br>"+
"CC Emails: " + JSON.stringify(data[i].cc_emails).replace("[]","No Emails are CC'd").replace("[","").replace("]","") + "<br>" +
"Ticket Creation Date: " + JSON.stringify(data[i].created_at) + "<br>" +
"Ticket Status: " + JSON.stringify(data[i].status).replace("2", "Open").replace("3", "Pending").replace("4", "Resolved").replace("5", "Closed").replace("6", "Waiting On Customer") ;
let pre = document.createElement('pre');
pre.innerHTML = text;
pre.style.cssText += 'font-size:24px;font-weight:bold;'
output.appendChild(pre);
console.log(pre)
}
})})
}
HTML:
<div class="ms-PanelExample">
<script src="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.4.0/js/fabric.min.js"></script>
<button style="margin:1px;" id="get-freshdesk" class="ms-Button ms-Button--primary">
<span class="ms-Button-label">Freshdesk Tickets</span>
</button>
<div class="ms-Panel ms-Panel--xxl">
<button class="ms-Panel-closeButton ms-PanelAction-close">
<i class="ms-Panel-closeIcon ms-Icon ms-Icon--Cancel"></i>
</button>
<div class="ms-Panel-contentInner">
<p class="ms-Panel-headerText">Freshdesk Integration</p>
<div class="ms-Panel-content">
<span class="ms-font-m">Latest Ticket information</span>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var PanelExamples = document.getElementsByClassName("ms-PanelExample");
for (var i = 0; i < PanelExamples.length; i++) {
(function() {
var PanelExampleButton = PanelExamples[i].querySelector(".ms-Button");
var PanelExamplePanel = PanelExamples[i].querySelector(".ms-Panel");
PanelExampleButton.addEventListener("click", function(i) {
new fabric['Panel'](PanelExamplePanel);
});
}());
}
</script>
Result from console:
Tracking Prevention blocked access to storage for https://appsforoffice.microsoft.com/lib/1/hosted/en-us/outlook_strings.js.
### yet it displays the pre information in the console below because I added console.log(pre)
I also tried adding the domains of where the api gets its data but I am still getting the error. I added it to the edge's exclusion list and I also added it to the manifest xml.
code that was added to the manifest xml to ensure that the api's domain is allow to get some data:
<!-- Domains that will be allowed when navigating. For example, if you use ShowTaskpane and then have an href link, navigation will only be allowed if the domain is on this list. -->
<AppDomains>
<AppDomain>https://freshdesk.com</AppDomain>
<AppDomain>https://alloysystems.freshdesk.com</AppDomain>
<AppDomain>AppDomain3</AppDomain>
</AppDomains>
<!--End Basic Settings. -->
I think I figured out the answer. The problem is that I added the javascript to my existing office apps javascript which has Office.onReady((info) => at the top of the script. If I add my javascript to the existing office apps javascript it will fail.
So I made a new javascript file and added that to the html. In the new file I used the javascript code above, then I simply added the script to the head tag and it started working.

AJAX Query to Web Service in SharePoint on Button Click

I am trying to have a button on a SharePoint form query the govt SAM web service. Basically, I want to be able to manually enter a value in the form, click an HTML button, to query that value from the open form, and then fill out the rest of the fields automatically and save the record in a SP list. I am just working on the query portion now. I have jquery embedded in my master page.
When I wrote all the logic in the browser console, everything works fine. I cannot get it to mesh up with the button. I get this error in the console.
"Uncaught SyntaxError: Unexpected token <" which makes no sense. Here is my script:
<script>
$("button").click(function () {
var SAM_Title = document.getElementById('Title_fa564e0f-0c70-4ab9-b863-
0177e6ddd247_$TextField').value;
var URL = "https://api.data.gov/sam/v1/registrations/" + SAM_Title +
"0000?api_key=xxxxxxxxxxxxxxxxxxxxxxx";
var SAM_AJAX = $.get(URL);
var SAM_JSON = SAM_AJAX.responseText;
var parsedJSON = JSON.parse(SAM_JSON);
var BusinessName = parse.sam_data.registration.legalBusinessname;
var StreetAddress =
parsedJSON.sam_data.registration.govtBusinessPoc.address.Line1;
var City = parsedJSON.sam_data.registration.govtBusinessPoc.address.City;
var ZIP = parsedJSON.sam_data.registration.govtBusinessPoc.address.ZIP;
}
</script>
Here is what I am putting in my script editor web part:
<html>
<script src="/SiteAssets/SAM_Query.js">
</script>
<body>
<button>Get External Content</button>
</body>
</html>
where SAM_Query.js is the above mentioned script.
I got it to work. The key was line 13 and cleaning up the syntax.
jQuery.noConflict();
jQuery( document ).ready(function() {
console.log( "jquery ready!" );
})
function samWebService() {
SAM_Title = document.getElementById('Title_fa564e0f-0c70-4ab9-b863-0177e6ddd247_$TextField').value;
console.log("DUNS: " + SAM_Title);
URL = "https://api.data.gov/sam/v1/registrations/" + SAM_Title + "0000?api_key=xxxxxxxxx";
console.log("URL: " + URL);
jQuery.ajaxSetup({ async: false });
SAM_AJAX = jQuery.get(URL);
console.log("SAM JSON response: " + SAM_AJAX);
SAM_JSON = SAM_AJAX.responseText;
console.log(SAM_JSON);
parsedJSON = JSON.parse(SAM_JSON);
console.log(parsedJSON);
BusinessName = parsedJSON.sam_data.registration.legalBusinessName;
StreetAddress = parsedJSON.sam_data.registration.mailingAddress.Line1;
City = parsedJSON.sam_data.registration.mailingAddress.City;
ZIP = parsedJSON.sam_data.registration.mailingAddress.Zip;
document.getElementById('Address_bc611d08-c16c-4ad9-a5b8-14388e176aba_$TextField').value=StreetAddress
document.getElementById('City_dd99bc74-382f-406c-aec0-8dc196b2c8ef_$TextField').value = City
document.getElementById('Business_x0020_Name_5eb60d17-9d0b-4243-92f5-81f5534e8bc0_$TextField').value = BusinessName
document.getElementById('ZIP_e078f52b-a0bc-4c95-a622-a16d6491b017_$TextField').value = ZIP
};
And calling the function with a clickable link.
<script src="/siteassets/lib/jquery/jquery.min.js"></script>
<script src="/test/SiteAssets/SAM_Query.js"></script>
Click Me!

Embed dynamically updated blog RSS Feed to Website

I have a website on one domain, and a blog hosted on blogspot. at the bottom of the homepage on my website, I want to embed a link to the latest post on my blogspot along with the respective article image and title. I have a function that used to work but since i have moved to blogspot, the RSS url is different from what i previously used, thus the function will not work as expected anymore. How can I work this function around the blogspot rss embed link ?? thanks
blogspot rss2.0 embed link
RSS 2.0: http://blogname.blogspot.com/feeds/posts/default?alt=rss
existing function:
<script src="js/jquery.min.js" type="text/javascript"></script>
<script>
function getRSS(link, number) {
$.ajax(link, {
accepts:{
xml:"application/rss+xml"
},
dataType:"xml",
success:function(data) {
var blogItemArray = $(data).find("item");
var blogItemOne = $(blogItemArray).get(0);
var blogTitleOne = $(blogItemOne).find("title").text();
var blogLinkOne = $(blogItemOne).find("link").text();
var blogDescOne = $(blogItemOne).find("description").text();
var blogImgOne = $(blogDescOne).find("img.hs-featured-image").get();
var blogImgSrcOne = $(blogImgOne).attr("src");
$("#blog-feed-link-" + number).attr("href", blogLinkOne);
$(".vertAlignerImg" + number).append( $('<img class="blog-img-link-'+ number +'" />' ));
$(".blog-img-link-" + number).attr("src", blogImgSrcOne);
$(".vertAligner" + number).append( $('<h2 />', {text: blogTitleOne}) );
}
});
}
$(document).ready(function() {
getRSS('rsslink', "One");
getRSS('rsslink', "Two");
});
</script>
'rsslink' used to be a url that ended in /rss.xml. now it looks like the link above. thanks!

how to transfer values between html pages?

I'm opening new page from anothe like this:
var openedwidow = window.open(billhref, '', 'scrollbars=1,height='+Math.min(h, screen.availHeight)+',width='+Math.min(w, screen.availWidth)+',left='+Math.max(0, (screen.availWidth - w)/2)+',top='+Math.max(0, (screen.availHeight - h)/2));
the second html page looks like this:
<div class="row contractor_data__item">
<label for="code">Номер</label>
<input type="text" name="code" id="code" disabled/>
<input type="hidden" name="documentId" id="documentId">
<input type="hidden" name="actId" id="actId">
<input type="hidden" name="actCode" id="actCode">
</div>
on the page opening in the new window I have a few fields to fill. For example, I've filled "code" field on the first page and need to fill the "code" field in the page opened. How to do this?
the second part of question is that I've filled some fields on the page opened, like documentId and need to pass it to the first page I've called this one from on close, for example or on the field filled. How to perfrorm this?
In HTML5 you can use session to pass object from page to another:
// Save data to sessionStorage
sessionStorage.setItem('key', 'value');
// Get saved data from sessionStorage
var data = sessionStorage.getItem('key');
// Remove saved data from sessionStorage
sessionStorage.removeItem('key')
For further reference you can check here
Edit:
Sample Code:
Page1.html
<!DOCTYPE html>
<html>
<head>
<title>Page1</title>
<script type="text/javascript">
sessionStorage.setItem("name","ShishirMax");
var fName = sessionStorage.getItem("name");
console.log(fName);
function myFunction(){
window.open("page2.html");
}
</script>
</head>
<body>
This is Page 1
</br>
<button onclick="myFunction()">SendThis</button>
</body>
</html>
Page2.html
<!DOCTYPE html>
<html>
<head>
<title>Page 2</title>
</head>
<body>
This is Page 2</br>
<input type="text" name="txtName" id="txtName" value="">
<script type="text/javascript">
var fName = sessionStorage.getItem("name");
console.log(fName);
document.getElementById("txtName").value = fName;
</script>
</body>
</html>
Try the following code for the test purpose.
hi if you want transfer data in some page you can use localStorage our sessionStorage in js
difference between sessionStorage clear when you close browser and localstorage will be clear only if you ask it
go refer to documentation for sintax e.g :
you value is stak in 'data' variable in this e.g
var data;
sessionStorage.setItem('nameyourvar', data);
after you can take on other page with :
sessionStorage.getItem('nameyourvar')
Use a query string. That's what they're for. Dont' forget to wrap your values in encodeURIcomponent in case they contain any special characters.
window.open("somewhere.html?firstname="+encodeURIComponent(firstname)+"&lastname="+encodeURIComponent(lastname)+"");
In the new window you can get the values from the query string like this
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var firstname = getParameterByName('firstname'); // "Bob"
var lastname = getParameterByName('lastname'); // "Dole"
Function is from here.
Since other people are mentioning localstorage, you should know that localstorage isn't supported in all browser. If you're interested in using something like that (you should really use query strings instead) you can check out this cross browser database Library I wrote.
Set your items to the database on the first page
jSQL.load(function(){
jSQL.createTable("UserData", [{FirstName: "Bob", LastName: "Dole"}]);
jSQL.persist(); // Save the data internally
});
Get your items from the second page
jSQL.load(function(){
var query = jSQL.query("SELECT * FROM `UserData`").execute();
var row = query.fetch("ASSOC");
var firstname = row.FirstName;
var lastname = row.LastName;
});
You can use GET parameters.
When you're opening second page, pass all the data you want to pass as GET parameters in the url, for example :
var billhref = "whatever.html?code=your_code&parameter2=parameter2_value" ;
var openedwidow = window.open(billhref, '', 'scrollbars=1,height='+Math.min(h, screen.availHeight)+',width='+Math.min(w, screen.availWidth)+',left='+Math.max(0, (screen.availWidth - w)/2)+',top='+Math.max(0, (screen.availHeight - h)/2));
Make a JS function to get parameters on the second page :
function getParams() {
var params = {},
pairs = document.URL.split('?')
.pop()
.split('&');
for (var i = 0, p; i < pairs.length; i++) {
p = pairs[i].split('=');
params[ p[0] ] = p[1];
}
return params;
}
Then use this function to get url parameters like this :
params = getParams();
for( var i in params ){
console.log( i + ' : ' + params[i] );
}
This will return output like :
code : your_code
parameter2 : parameter2_value
Using PHP will help you get around this problem with even shorter code
For example, in PHP, to get the parameters code, you'll just have to write :
$code = $_GET['code'];
And it will give you assign a variable named code the value you have passed in the url against code parameter( your_code in this example ).

Advert delivery via Javascript document.write

I'm building an advert delivery method and am try to do it through an external Javascript/jQuery page.
I have this so far, but I have some issues with it
$.get('http://url.com/ad.php', {
f_id: _f_id,
f_height: _f_height,
veloxads_width: _f_width
}, function (result) {
var parts = result.split(",");
var path = parts[0],
url = parts[1];
document.write('<img src="' + path + '">');
I can see the page load, but then after the code above is loaded, it creates a new page with just the advert on it. Is there anyway I can write it onto the page where the code was put?
And this is the script web masters put on their websites to include the adverts:
<script type="text/javascript">
var _f_id = "VA-SQ2TDEXO78N0";
var _f_width = 728;
var _f_height = 90;
</script>
<script type="text/javascript" src="http://website.com/cdn/addelivery.js"></script>
Cheers
is ad.php on the same domain as your script? if it's not have a look at this article
here is a code you could use in your html page, where you want the ad to be inserted:
$.get('http://url.com/ad.php',
{ f_id : _f_id, f_height : _f_height, veloxads_width : _f_width }
).success(function(result) {
var parts = result.split(",");
var path = parts[0], url = parts[1];
$('body').prepend('<div id="ad_id"><img src="'+path+'"></div>');
});
the selector (body here) can be an id, a class, ... (see documentation). You can also use prepend() or html() instead of append, to insert the code where you want ;)

Categories