webkit and mozilla full-screen mode - fullscreen

I know this has only just been introduced lately, so if I use it, how can I test if a browser supports it?
If I do something like the following, I believe I am testing if the browser is in full screen mode not whether or not the browser offers the functionality?
function FullScreenSupported() {
if (document.webkitIsFullScreen) {
alert("webkitIsFullScreen is supported");/
} else {
alert("webkitIsFullScreen is not supported");
}
}
Mozilla’s introduction to full screen mode is here: Using fullscreen mode – AutoCompatibilityTable
.

I found here a function that makes use of Modernizr to do that.
I refactored the code to make it work without Modernizr too:
function FullScreenSupported() {
var ancelFullScreen = 'ancelFullScreen';
// FF9 pre-check
if(document.mozCancelFullScreen && !document.mozFullScreenEnabled) {
return false;
}
domPrefixes = [ 'moz', 'webkit' ];
var limit = domPrefixes.length;
for(var i = 0; i < limit; ++i) {
if(document[domPrefixes[i].toLowerCase() + 'C' + ancelFullScreen])
return true;
}
return !!document['c' + ancelFullScreen] || false;
};
I've tested it with Firefox 19, Chrome 25, Safari 5, IE8 and it seems to work :)

Related

instagram embed doesn't work at first when dynamically appending into a page, but then works after refresh

Go to:
http://staging2.ju.blog.kylebaker.io/
click hamburger
click 'timeline'
instagram embeds show only the gray logo and don't load fully. embed.js doesn't seem to load when watching in the network tab.
Now, click refresh.
Now, everything loads. embed.js is there.
:/
You can notice that an older version on http://staging.ju.blog.kylebaker.io works fine--this seems to obviously be because it's an entirely new page load (which I want to avoid).
Some potentially relevant code this theme relies on to load this page "into" the page:
L: function(url, f, err) {
if (url == xhrUrl) {
return false;
}
xhrUrl = url;
if (xhr) {
xhr.abort();
}
xhr = $.ajax({
type: 'GET',
url: url,
timeout: 10000,
success: function(data) {
f(data);
xhrUrl = '';
},
error: function(a, b, c) {
if (b == 'abort') {
err && err()
} else {
window.location.href = url;
}
xhrUrl = '';
}
});
},
HS: function(tag, flag) {
var id = tag.data('id') || 0,
url = tag.attr('href'),
title = tag.attr('title') + " - " + $("#config-title").text();
if (!$('#preview').length || !(window.history && history.pushState)) location.href = url;
Diaspora.loading()
var state = {d: id, t: title, u: url};
Diaspora.L(url, function(data) {
if (!$(data).filter('#single').length) {
location.href = url;
return
}
switch (flag) {
case 'push':
history.pushState(state, title, url)
break;
case 'replace':
history.replaceState(state, title, url)
break;
}
document.title = title;
$('#preview').html($(data).filter('#single'))
switch (flag) {
case 'push':
Diaspora.preview()
break;
case 'replace':
window.scrollTo(0, 0)
Diaspora.loaded()
break;
}
setTimeout(function() {
Diaspora.player();
$('#top').show();
comment = $("#gitalk-container");
if (comment.data('ae') == true){
comment.click();
}
}, 0)
})
},
preview: function() {
// preview toggle
$("#preview").one('transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd', function() {
var previewVisible = $('#preview').hasClass('show');
if (!!previewVisible) {
$('#container').hide();
}else{
$('#container').show();
}
Diaspora.loaded();
});
setTimeout(function() {
$('#preview').addClass('show');
$('#container').data('scroll', window.scrollY);
setTimeout(function() {
$('#preview').css({
'position': 'static',
'overflow-y': 'auto'
});
}, 500);
}, 0);
},
(for full file, see: https://github.com/Fechin/hexo-theme-diaspora/blob/master/source/js/diaspora.js)
I see the script tag loaded in the DOM; why isn't it loading? Feels like it must be something simple I'm missing... It's 4am and I've been working non-stop.
(please ignore the dust, this is a small side-project work-in-progress with many small things broken.)
Things I've tried:
adding the code to load embed.js manually in the page. (no change--I then see embed.js is loaded, but it doesn't have an impact on the result)
editing the URL to include "http:" before the "//insta..." url (as
recommended in some answers elsewhere for some people) (no change)
window.instgrm.Embeds.process() it seems the instgrm object no longer exists. (no change)
Seems to be related to however this is being injected via jquery, but I'm a little confused as to specifics, figured I'd ask the world and make a space for the answer to exist for the next poor soul.
Note that because of what I've tried, the answers here do not seem to be helpful or relevant, though maybe it's just me blanking at 4am.
The problem was, indeed, the things I had already addressed, I just missed some rendering details of getting changes to stick. jQuery executing and stripping the script tags seems to have been the source the problem, and calling window.instgrm.Embeds.process() at the appropriate time, after making sure that the embeds.js script was requested in the right place/at the right time, was enough to fix the issue seen above. Part of the confusion was using hexo, which uses ejs in node, which doesn't really seem to allow client-executing inline JS in ejs template files themselves, silently.

Userscript works in Tampermonkey on Chrome and Firefox, but doesn't work in Greasemonkey on Firefox

This script works just fine in Tampermonkey on both Chrome and Firefox, but doesn't work in Greasemonkey on Firefox. When I say it doesn't work I mean the button does not show up on the page. I'm using Chrome 61.0.3163.79 and Firefox 52.3.0.
The firefox console shows this warning but I'm not sure if it's relevant:
unreachable code after return statement[Learn More] jquery-1.3.2.min.js
Here's the code. Using greasemonkey on Firefox, I see "create button" in the console, but not "button has been created", which makes me think something is going wrong with the button creation. Any help greatly appreciated!
// ==UserScript==
// #name MyScript
// #namespace MyNS
// #description Adds a button to insert text into 2 text boxes
// #version 0.1
// #include *Removed for confidentiality*
// #compatible Greasemonkey
// ==/UserScript==
var descriptionText = "myDescription";
var testingText = "myTesting";
// Check if jQuery's loaded
function GM_wait() {
if (typeof unsafeWindow.jQuery == 'undefined') { window.setTimeout(GM_wait,100); }
else { $ = unsafeWindow.jQuery; init(); }
}
// All your GM code must be inside this function
function init() {
var description = $('#description');
var testingDone = $('#testing_done');
function insertText(template, editor) {
if (template) {
if (!editor._editing) {
editor.startEdit();
}
editor._field.queue(function() {
var oldVal = editor._field.val();
editor._field.val(template + (oldVal ? "\n" : "") + oldVal);
editor._field.keyup();
editor._field.dequeue();
});
}
}
function createButton(editor) {
console.log("create button:");
editor._insertTextButton = $('<input/>')
.attr('type', 'button')
.attr('value', 'Insert CR Template')
.css('margin-left', '1em')
.click(function() {
insertText(testingText, testingDoneEditor);
insertText(descriptionText, descriptionEditor);
});
console.log("button has been created");
editor._insertTextButton.insertAfter(editor._editIcon);
}
descriptionEditor = description.data('inlineEditor');
testingDoneEditor = testingDone.data('inlineEditor');
createButton(descriptionEditor);
}
GM_wait();

Can I detect fullscreen in a Chrome extension?

I have a Chrome extension (specifically, a "content script") where I'd like to detect whether the page I am monitoring/changing is in fullscreen state. I have tried several APIs, as well as the "screenfull" library, but no luck so far. Any ideas?
Thanks for your help!
If you want to detect whether the page has used the Fullscreen API to enter fullscreen mode, just check document.webkitIsFullscreen.
If you want a general method to reliably detect full screen mode, the chrome.windows API is your only option. Since this API is unavailable to content scripts, you need to use the message passing API to interact with a background or event page.
Example: content script
function isFullScreen(callback) {
chrome.runtime.sendMessage('getScreenState', function(result) {
callback(result === 'fullscreen');
});
}
// Example: Whenever you want to know the state:
isFullScreen(function(isFullScreen) {
alert('Window is ' + (isFullScreen ? '' : 'not ') + 'in full screen mode.');
});
Example: background / event page
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message === 'getScreenState') {
chrome.windows.get(sender.tab.windowId, function(chromeWindow) {
// "normal", "minimized", "maximized" or "fullscreen"
sendResponse(chromeWindow.state);
});
return true; // Signifies that we want to use sendResponse asynchronously
}
});
You can try something like this:
var isFullScreen = (screen.width == window.outerWidth) && (screen.height == window.outerHeight);
if(isFullScreen) {
// ...
}
The simplest way is to listen for webkitfullscreenchange event, e.g
$(document).on('webkitfullscreenchange',function(){
if (document.webkitIsFullScreen === true) {
console.log('Full screen mode is on");
} else {
console.log('Full screen mode is off");
}
});

Using userscript GM_functions inside the page context

I want to "re-link" everything in a specific page through a XMLHTTPRequest to a local network domain. That would lead me to GM_xmlhttpRequest in GreaseMonkey/NinjaKit except that I want to run it when the link is clicked, not when the userscript actually runs...
So I have something like:
links = document.getElementsByTagName('a');
for (i = 0; i < links.length; i++) {
oldhref = links[i].getAttribute('href');
links[i].setAttribute('href', 'javascript:loadLink(' + oldhref + ')');
}
I understand I can either use unsafeWindow or add a script element to document to inject loadLink function.
But how can I use GM_xmlhttpRequest in loadLink?
I've looked at 0.7.20080121.0 Compatibility page but I'm not sure if that is for what I need...
I've also considered adding an iframe to the page and the modified links would load inside the iframe (triggering the userscript again), but I'd prefer a cleaner solution...
You almost never need to use GM functions inside the page context, and from the code posted so far, you don't need unsafeWindow in this case either.
Also, it is not necessary to rewrite the href for what is posted so far.
Something like this will accomplish what you want:
var links = document.getElementsByTagName ('a');
for (var J = 0, len = links.length; J < len; ++J) {
links[J].addEventListener ("click", myLoadLink, false);
}
function myLoadLink (zEvent) {
zEvent.preventDefault();
zEvent.stopPropagation();
var targetHref = zEvent.currentTarget.getAttribute ('href');
GM_xmlhttpRequest ( {
//wtv
} );
return false;
}
Or with jQuery:
$("a").click (myLoadLink);
function myLoadLink () {
var targetHref = $(this).attr ('href');
GM_xmlhttpRequest ( {
//wtv
} );
return false;
}
Ok, so I managed to get that GreaseMonkey official workaround working (dunno what I did wrong the first time) with:
unsafeWindow.loadLink = function(href) {
setTimeout(function(){
GM_xmlhttpRequest({
//wtv
});
},0);
}
But I'd still prefer a solution without using unsafeWindow if there is one... (especially since this one feels so wrong...)

How to tell if a script is run as content script or background script?

In a Chrome extension, a script may be included as a content script or background script.
Most stuff it does is the same, but there are some would vary according to different context.
The question is, how could a script tell which context it is being run at?
Thank you.
I think this is a fairly robust version that worked in my initial tests and does not require a slower try catch, and it identifies at least the three primary contexts of a chrome extension, and should let you know if you are on the base page as well.
av = {};
av.Env = {
isChromeExt: function(){
return !!(window['chrome'] && window['chrome']['extension'])
},
getContext: function(){
var loc = window.location.href;
if(!!(window['chrome'] && window['chrome']['extension'])){
if(/^chrome/.test(loc)){
if(window == chrome.extension.getBackgroundPage()){
return 'background';
}else{
return 'extension';
}
}else if( /^https?/.test(loc) ){
return 'content';
}
}else{
return window.location.protocol.replace(':','');
}
}
};
Well I managed to work out this:
var scriptContext = function() {
try {
if (chrome.bookmarks) {
return "background";
}
else {
return "content";
}
}
catch (e) {
return "content";
}
}
It's because an exception would be thrown if the content script tries to access the chrome.* parts except chrome.extension.
Reference: http://code.google.com/chrome/extensions/content_scripts.html
The best solution I've found to this problem comes from over here.
const isBackground = () => location.protocol === 'chrome-extension:'
The background service worker at Manifest v3 does not contain a window.
I use this as part of my extension error handling which reloads the content scripts, when i receive an Extension context invalidated error:
...
if (!self.window) {
console.warn('Background error: \n', error);
} else {
location.reload();
}
...

Resources