Posting a status message to Facebook? - html

There's so many questions regarding Facebook's sharer.php, but they're all out of date. At first Facebook depreciated it, but according to FB's dev documentation it's now back. (Edit: And now it's going again...?)
You used to be able to use it like this:
http://www.facebook.com/sharer/sharer.php?u=<url to share>&t=<message text>
But the documentation now only mentions this:
https://www.facebook.com/sharer/sharer.php?u=<url to share>
Is it possible to set some pre-entered text into the dialogue box that appears when sharing a link on Facebook?
Thanks.

The Share dialog takes only the URL to share as parameter, nothing else (title, description, picture, …) any more. It fetches this data from the URL itself, from the Open Graph meta elements embedded into the document, or it takes a “guess” from the content if those are not present.
And even the “older” version of the Share dialog has not been taking a pre-set message parameter for a long time now – because you are not supposed to pre-fill the message in any way when sharing something, not matter what way the share actually happens. (“Not supposed to” actually meaning, Platform Policies explicitly forbid you from doing so.)
You can of course also share links via API (rather called “posting” a link then) – and because that happens in the background, the message is a parameter you specify while doing so. But the same rules apply – the message is supposed to be created by the user themselves beforehand, which effectively means they should have typed it in somewhere before. And even there it should not have been pre-filled so that they just have to press enter or click a button.
And since they announced API v2.0, all new apps will have to go through “login review” before they will be able to ask for any advanced permission (and posting a link requires one) – and with a pre-filled message in your app’s posting flow, you will definitively not get approval. Of course, you could try to “cheat” on that, and implement the pre-filling of the message only afterwards … but again, doing so is a clear violation of Platform Policies, and will get your app blocked when you are caught doing so.
And if you are planning to do this for multiple users with the same or largely similar messages, you can assume that Facebook’s algorithms will catch that quite easily.

Just one small comment - while it is not possible to edit the text as the other comments say - it is possible to edit everything going on in that page if you can install a browser extension on your client's machines (you did not specify your use case so I am mentioning this just in case you are developing something that you are able to influence in the client machine level).
For example, with a chrome extension, you can inject scripts into facebook.com domain. in the extension manifest.json:
"content_scripts": [
{
"matches": ["https://*.facebook.com/*",
And then this might be your contnet script, where you can play around with the text by hooking up to the markeup. This example sends out analytics (facebook sharer conversion rate) and changes some text (from "share" to "upload" to facebook):
sharer = (function () {
var _ref = qs('ref') ? qs('ref') : 'unknown';
function qs(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
function isSharer() {
return location.pathname === '/sharer/sharer.php';
}
function bindEvents() {
$('button[name="share"]').click(function() {
analytics.send('fb_sharer', 'share', _ref);
});
$('#u_0_0').click(function() {
analytics.send('fb_sharer', 'cancel', _ref);
});
}
function changeText() {
console.log($('.fcw').length);
$('.fcw').text('Upload to Facebook');
}
function load() {
if (!isSharer()) return;
changeText();
analytics.send('fb_sharer', 'view', _ref);
bindEvents();
}
return {
load: load
}
})();

Related

Programmatic injection on nested iframes in extension page

Summary: I need to find a way to accomplish with programmatic injection the same exact behaviour as using content_scripts > matches with "all_frames": true on a manifest. Why? because it is the only way I've found of injecting iframe's content in an extension page without having Cross-Origin errors.
I'm moving to optional_permissions on a Chrome extension and I'm on a dead end.
What I want:
Move this behaviour to optional_permissions in order to be able to add more hosts in the future. With the current code, by adding one new host on content_scripts > matches the extension is disabled by Chrome.
For the move, I removed content_scripts in the manifest and I added "optional_permissions": ["*://*/"],. Then, I successfully implemented a dialog asking new permissions to the user with chrome.permissions.request.
As I said before, the problem is how to inject the iframe's content in an extension page.
What I've tried:
chrome.declarativeContent.RequestContentScript (mentioned here) with allFrames: true. I can only see the script running if I enter the URL directly, nothing happens when that URL is set in an iframe.
chrome.tabs.onUpdated: url is undefined for an extension page. Also, the iframe url is not detected.
Call chrome.tabs.executeScript with allFrames: true as soon as I load the first iframe. By doing this I get an exception Cannot access contents of the page. Extension manifest must request permission to access the respective host. and the "respective host" is chrome-extension://, which is not a valid host if you want to add it to the permissions.
I'm lost. I couldn't find a way to simulate the same behaviour as content_scripts > matches with programmatic injection.
Note: using webNavigation API is not an option since the extension is live and it has thousands of users. Because of this, I can not use the frameId property for executeScript. Thus, my only option with executeScript was to inject all frames but the chrome-extension host issue do not let me continue.
Update: I was able to accomplish what I wanted but only on an HTTP host. I used chrome.tabs.executeScript (option 3).
The question remains on how to make this work on an extension page.
You cannot run content scripts in any extension page, including your own.
If you want to run code in a subframe of your extension page, then you have to use frameId. There are two ways to do this, with and without webNavigation.
I've put all code snippets in this answer together (with some buttons to invoke the individual code snippets) and shared it at https://robwu.nl/s/optional_permissions-script-subframe.zip
To try it out, download and extract the zip file, load the extension at chrome://extensions and click on the extension button to open the test page.
Request optional permissions
Since the goal is to programmatically run scripts with optional permissions, you need to request the permission. My example will use example.com.
If you want to use the webNavigation API too, include its permission in the permission request too.
chrome.permissions.request({
// permissions: ['webNavigation'], // uncomment if you want this.
origins: ['*://*.example.com/*'],
}, function(granted) {
alert('Permission was ' + (granted ? '' : 'not ') + 'granted!');
});
Inject script in subframe
Once you have a tab ID and frameId, injecting scripts in a specific frame is easy. Because of the tabId requirement, this method can only work for frames in tabs, not for frames in your browserAction/pageAction popup or background page!
To demonstrate that code execution succeeds, my examples below will call the next injectInFrame function once the tabId and frameId is known.
function injectInFrame(tabId, frameId) {
chrome.tabs.executeScript(tabId, {
frameId,
code: 'document.body.textContent = "The document content replaced with content at " + new Date().toLocaleString();',
});
}
If you want to run code not just in the specific frame, but all sub frames of that frame, just add allFrames: true to the chrome.tabs.executeScript call.
Option 1: Use webNavigation to find frameId
Use chrome.tabs.getCurrent to find the ID of the tab where the script runs (or chrome.tabs.query with {active:true,currentWindow:true} if you want to know the current tabId from another script (e.g. background script).
After that, use chrome.webNavigation.getAllFrames to query all frames in the tab. The primary way of identifying a frame is by the URL of the page, so you have a problem if the framed page redirects elsewhere, or if there are multiple frames with the same URL. Here is an example:
// Assuming that you already have a frame in your document,
// i.e. <iframe src="https://example.com"></iframe>
chrome.tabs.getCurrent(function(tab) {
chrome.webNavigation.getAllFrames({
tabId: tab.id,
}, function(frames) {
for (var frame of frames) {
if (frame.url === 'https://example.com/') {
injectInFrame(tab.id, frame.frameId);
break;
}
}
});
});
Option 2: Use helper page in the frame to find frameId
The option with webNavigation looks simple but has two main disadvantages:
It requires the webNavigation permission (causing the "Read your browsing history" permission warning)
The identification of the frame can fail if there are multiple frames with the same URL.
An alternative is to first open an extension page that sends an extension message, and find the frameId (and tab ID) in the metadata that is made available in the second parameter of the chrome.runtime.onMessage listener. This code is more complicated than the other option, but it is more reliable and does not require any additional permissions.
framehelper.html
<script src="framehelper.js"></script>
framehelper.js
var parentOrigin = location.ancestorOrigins[location.ancestorOrigins.length - 1];
if (parentOrigin === location.origin) {
// Only send a message if the frame was opened by ourselves.
chrome.runtime.sendMessage(location.hash.slice(1));
}
Code to be run in your extension page:
chrome.runtime.onMessage.addListener(frameMessageListener);
var randomMessage = 'Random message: ' + Math.random();
var f = document.createElement('iframe');
f.src = chrome.runtime.getURL('framehelper.html') + '#' + randomMessage;
document.body.appendChild(f);
function frameMessageListener(msg, sender) {
if (msg !== randomMessage) return;
var tabId = sender.tab.id;
var frameId = sender.frameId;
chrome.runtime.onMessage.removeListener(frameMessageListener);
// Note: This will cause the script to be run on the first load.
// If the frame redirects elsewhere, then the injection can seemingly fail.
f.addEventListener('load', function onload() {
f.removeEventListener('load', onload);
injectInFrame(tabId, frameId);
});
f.src = 'https://example.com';
}

How to make screen blink when there is an unread email

I am looking for any way to make the entire screen blink red, or whatever color, when there is an unread email. It could be for any email client. I have done a lot of googling and can't find anything. There is an add-on to thunderbird that creates a little blinking notification, but it only appears very small in the lower right hand corner of the screen.
I was thinking of maybe some add-on to Firefox or Chrome that would allow me to write custom css and javascript that would run on Gmail and make the blinking happen.
Any ideas are greatly appreciated.
I know this is not you regular SO question, but y'all are great and I don't know where else to turn. If there is a better forum out there for this type of question, you could also inform me of it.
Thanks!
I have found this program while searching, haven't tried it. But it says it can execute an external program when email arrives. So seems like you can write a little C# application that can perform the task you want and execute when new email arrives.
http://www.jsonline.nl/Content/Poppy/Poppy.htm
Instead of making a Chrome plugin, I would either make the window title blink or use HTML5 Notifications. Create a simple page which polls your IMAP Gmail for new messages, and include gmail in a large iFrame. If a new message is found, your outer window can issue the notification.
HTML5 Notifications: http://www.html5rocks.com/en/tutorials/notifications/quick/
Blinking Title (adopted from this):
var newMailBlinker = (function () {
var oldTitle = document.title,
msg = 'New Mail!',
timeoutId,
blink = function() {
document.title = document.title == msg ? ' ' : msg;
},
clear = function() {
clearInterval(timeoutId);
document.title = oldTitle;
window.onmousemove = null;
timeoutId = null;
};
return function () {
if (!timeoutId) {
timeoutId = setInterval(blink, 1000);
window.onmousemove = clear;
}
};
}());
PHP Poll Gmail IMAP (adopted from this):
$t1=time();//mark time in
$tt=$t1+(60*1);//total time = t1 + n seconds
do{
if(isset($t2)) unset($t2);//clean it at every loop cicle
$t2=time();//mark time
if(imap_num_msg($imap)!=0){//if there is any message (in the inbox)
$mc=imap_check($imap);//messages check
//var_dump($mc); die;//vardump it to see all the data it is possible to get with imap_check() and them customize it for yourself
echo 'New messages available';
}else echo 'No new messagens';
sleep(rand(7,13));//Give Google server a breack
if(!#imap_ping($imap)){//if the connection is not up
//start the imap connection the normal way like you did at first
}
}while($tt>$t2);//if the total time was not achivied yet, get back to the beginning of the loop
jQuery AJAX Polling to your IMAP script (adopted from this):
// make the AJAX request
function ajax_request() {
$.ajax({
url: '/path/to/gmail/imap/checkMessages.php',
dataType: 'json',
error: function(xhr_data) {
// terminate the script
},
success: function(xhr_data) {
console.log(xhr_data);
if (xhr_data.status == 'No new messages') {
setTimeout(function() { ajax_request(); }, 15000); // wait 15 seconds than call ajax request again
} else {
newMailBlinker(); // blink the title here for new messages
}
}
contentType: 'application/json'
});
}
Obviously you wouldn't use jQuery AND PHP to poll. Pick one to do the polling. I'd recommend have the client do the polling and have PHP check IMAP once per connection. That being said, these snippets should get you started :)
Grab the current google mail checker extension sample (https://developer.chrome.com/extensions/samples.html). Convert it to a packaged app (grab the pieces you want), open a very large window and close it quickly. That should do the trick. Sadly Fullscreen doesnt seem to be possible. But i dont know if thats a problem.
Assuming your dad has the client page always opened, you could just write an extension and manipulate the screen with JS.
You could for example:
Use the gmail client in chrome
Write a chrome extension that checks for new e-mails that come in. You could achieve this by identifying new e-mails. I believe gmail uses a specific css class for new e-mails. So your JS just needs to check for that class.
Have the extension change the page from white to red and back to white a few times (or till the e-mail is read).
You could also possibly have the chrome extension play a sound when a new email arrives?
I found chrome extensions a lot easier to use than FF, especially if you're just going to use JS.

Usability issue for navigator.geolocation: how to know if the user is being asked for location?

Does HTML's navigator.geolocation have an event handler for 'Currently asking the user if they will share their location'?
I would like to show some text instructing the user to share their location if and only if they are actually being asked to share their location.
Currently I have this code, but it's broken.
It looks smooth the first time, but the second time (when the browser knows this is a trusted site, so doesn't ask the user about sharing their location), 'Share your location' flashes up quickly when the page loads, then disappears behind the map.
// map.js
function gpsSuccess() {
// We have a location - although we don't know whether this is
// because the user has already agreed to share with this domain,
// or whether they have just this second been asked.
$('#sharelocation').hide();
// load map, etc
}
if (navigator.geolocation) {
watchId = navigator.geolocation.watchPosition(gpsSuccess, gpsFail);
}
// map.html
<div id="sharelocation">Share your location</div>
<div id="map" class="hidden"></div>
Any suggestions for a smooth way to give the user some instructions in the body of the page if and only if they are actually being asked to share their location?
I'd consider not showing the "Share Location" message unless the failure callback gets executed.
function gpsFail() {
$('#sharelocation').show();
}
You can include a message in the sharelocation block which explains how to enable location sharing, what you'll do with the information, etc.
Sounds like you might just have a timing issue with the brief delay between getCurrentPosition and your callback. What if you delay the show by a second or so? (I don't know what the jquery-specific method is) Keep a reference to the task so in gpsSuccess you can call clearTimeout with it.

Chrome open address in tab

I am trying to create a simple adult filter to get my feet wet in Chrome extension building.
Basically, I have a block list and a redirect list, everything works great and the correct parts fire when the user enters one of block list's domains, and now i want to redirect to google when that happens, so I used this code (that I got after searching Google) :
if (blocked) {
up = new Object();
up.url = chrome.extension.getURL("http://www.google.com");
chrome.tabs.update(tab.id, up);
but that seems to be code only to open files locally.
How do I open the URL instead?
Thanks!
Since "http://www.google.com" is not an extension resource, just use:
up.url = "http://www.google.com";

How to use google analytics with HTML 5 History?

I'm using HTML 5 history for my site, so, for users whose browsers support it, clicking on a link doesn't reload the whole page, but just the main area.
Google analytics doesn't track these partial page loads. How can I get it to track it just like it does for users that don't have HTML 5 history support?
You just need to register the additional pageviews by calling the _trackPageview function again each time your new content loads. This is called a 'Virtual Pageview' but is registered in Google Analytics in the same way as a real one. To set the path of the page you need to add an additional parameter to the function:
_gaq.push(['_setAccount', 'UA-XXXXXXX-X']);
_gaq.push(['_trackPageview', '/new/content']);
This is for the newest Universal Tracking Code.
So recently, I had to revisit my own answer for a new project. I noticed some issues that I should clean up.
To send a pageview programmatically, you want to send only the Path and the Query eg. for http://example.com/path/to/resource?param=1 we will send /path/to/resource?param=1.
Some SPAs use HashBangs (#!) for their urls. So we need to send anything after the Hashbang. e.g. http://example.com#!path/to/resource we will send /path/to/resource?param=1.
The earlier version of my solution was erroneous and would fail for all urls which had a hash in the url. Also, as I was using jQuery + History.js plugin my solution was along of listening to statechange came from there.
Use this new code to send a pageview. It is more resilient and caters for both hashbangs and history.
var loc = window.location,
hashbang = "#!",
bangIndex = location.href.indexOf(hashbang),
page = bangIndex != -1 ? loc.href.substring(bangIndex).replace(hashbang, "/") : loc.pathname + loc.search;
ga('send', 'pageview', page);
If you don't use Hashbangs specifically, simply change hashbang = "#!", to match e.g. hashbang = "##",
The second part of this is detecting when the url changes. For this, you will need to find out from the docs of whatever library you are using.
For jQuery + History.js plugin, the code below works
$(window).on('statechange', function() {
//put code here
});
More information can be found at https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications
$(window).on('statechange', function() {
var loc = window.location,
page = loc.hash ? loc.hash.substring(1) : loc.pathname + loc.search;
ga('send', 'pageview', page);
});
As Ewan already stated, you should send the pageview to analytics in the window.popstate event.
So, in plain javascript, if you have called:
history.pushState({'statedata':''}, 'title', '/new/page/url');
you should simply add:
window.addEventListener('popstate', function(event) {
ga('send', 'pageview');
});
Actually the new Universal Tracking Code automatically gets the current URL, so you don't really need to pass the extra parameter.