Chrome App web view using Fullscreen & Alwaysontop - google-chrome

I'm working on a Chrome app that opens up using the web view and loads our webpage. I'm trying to make a app that will lock down the web view so when someone is taking a test they can't get out of it or use something else to try and cheat. So the issue I'm having right now is I can't get the Full screen and AlwaysOnTop to work with each other. Is there a way to do this or will these two things not work together and if not is there a hack to get them to work or maybe another direction I need to take. I'm currently running my app with the Chrome Beta since alwaysOnTop doesn't work with the stable version yet. Here is the code in my
main.js
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create('browser.html', {
state: "fullscreen",
"resizable": false,
'alwaysOnTop': true
},
function(win) {
win.contentWindow.document.addEventListener('keydown', function(e) {
if(e.keyCode == 27){
e.preventDefault();
}
});
win.contentWindow.document.addEventListener('keyup', function(e) {
if(e.keyCode == 27){
e.preventDefault();
}
});
});
});
Any help or some type of direction would be great. I've only been able to get the alwaysontop to work when setting bounds instead but this will display the minimize maximize and exit which kind of defeats the purpose of what I'm trying to do. Thanks in advanced.

you might want to have a look at the "overrideEscFullscreen" permission.
See https://code.google.com/p/chromium/codesearch#chromium/src/chrome/test/data/extensions/platform_apps/prevent_leave_fullscreen_old/manifest.json&q=overrideEscFullscreen&sq=package:chromium&type=cs
manifest.json
{
"name": "Test app for leaving fullscreen rules",
"version": "1",
"app": {
"background": {
"scripts": ["main.js"]
}
},
"permissions": [
"fullscreen", "overrideEscFullscreen"
]
}
main.js
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create('main.html', {}, function(win) {
// The following key events handler will prevent the default behavior for
// the ESC key, thus will prevent the ESC key to leave fullscreen.
win.contentWindow.document.addEventListener('keydown', function(e) {
e.preventDefault();
});
win.contentWindow.document.addEventListener('keyup', function(e) {
e.preventDefault();
});
});
});

Related

Cache cleaning not entering the function

i am trying to clean my cache in a web application, so, i erase my css and put this function in my all.js archive, below document.ready:
// Check if a new cache is available on page load.
window.addEventListener('load', function(e) {
console.log("entered the function");
window.applicationCache.addEventListener('updateready', function(e) {
console.log("entered the function 2");
if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
// Browser downloaded a new app cache.
// Swap it in and reload the page to get the new hotness.
window.applicationCache.swapCache();
if (confirm('A new version of this site is available. Load it?')) {
window.location.reload();
}
} else {
// Manifest didn't changed. Nothing new to server.
}
}, false);
}, false);
the problem is, it don't cleans my cache, after erase my css it still shows the old one, and the console.log("entered the function 2") is not printing as well.
can anybody helps, please?
thank you a lot!
I solve my problem doing:
// Check if a new cache is available on page load.
window.addEventListener('beforeload', function(e) {
if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
// Browser downloaded a new app cache.
// Swap it in and reload the page to get the new hotness.
window.applicationCache.swapCache();
window.location.reload();
}
}, false);
don't think is the right way, but works

"ok" button missing in iOS7 with Cordova on "select prompt"

I got a Cordova IOS7 APP where I have a default HTML "select" -
When the select prompt shows there is NO "ok" or "done" button to close it again, in iOS6 it works fine, and the same with the buildin Safari browser.
So, can anyone tell me what the problem is?
Cordova APP
Safari browser
Finally i got it.
Simple answer -
Set this to "false"
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(false);
http://forum.ionicframework.com/t/select-dropdown-issue-on-ios/5573/3
You can show and hide the accessory bar on demand which is explained better here (but it worked better for me by taking out the $timeouts in the directive). Here's what mine looks like.
.directive('select', function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
element.bind('focus', function(e) {
if (window.cordova && window.cordova.plugins.Keyboard) {
// console.log("show bar (hide = false)");
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(false);
}
});
element.bind('blur', function(e) {
if (window.cordova && window.cordova.plugins.Keyboard) {
// console.log("hide bar (hide = true)");
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
});
}
};
})

Chrome Extensions: Extension not working - Content Script Communicating with Background Script

I am working on a Chrome Extension which changes the Browser Action Icon to "red.png" or "green.png" (which are both saved in the same directory as all other files) when the browser app detects sound is being played from an <audio> html5 tag.
My logical thought process is: User opens page, script starts running on page which constantly (perhaps a setInterval()) checks for if the sound is running. If the sound is running, change the icon to "green.png", else, set it to "red.png".
The way I am checking if sound is being played is this:
if (audio.duration > 0 && !audio.paused)
Where audio is a variable holding the <audio> element.
Here is my code:
manifest.json file:
{
"name": "Creative Sound Dedection",
"description": "Creatively detects sound.",
"version": "1.0",
"permissions": [
"activeTab"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_icon": "red.png"
},
"content_scripts" : [
{
"matches" : [ "<all_urls>" ],
"js" : [ "myscript.js" ]
}
],
"manifest_version": 2
}
background.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
var playing = request.playing;
if(playing == true)
{
chrome.browserAction.setIcon({path:"green.png"});
}else{
chrome.browserAction.setIcon({path:"red.png"});
}
});
myscript.js
function isAudioPlaying(var audio)
{
if (audio !== false && audio.duration > 0 && !audio.paused)
{
return true;
}
return false;
}
function getAudio()
{
if(document.getElementById("myAudio")) return document.getElementById("myAudio");
return false;
}
//if audio is playing: tell background that audio is playing, otherwise, tell it audio is not playing
function sendInfo()
{
chrome.runtime.sendMessage({
"playing": true
});
}
document.addEventListener('DOMContentLoaded', function () {
setInterval(sendInfo, 500);
});
I'm looking for help with why this isn't working and how to correct it, I'm very new to Chrome Extensions development as well as Javascript (although not necessarily new to programming).
Also if you can think of other ways (better) to accomplish the same task please let me know.
Any input would be greatly appreciated!
UPDATE:
Furthermore, the expression playing == true will always evaluate to false, since playing is a string. So:
// Change that:
var playing = request.playing;
if (playing == true) {...
// To this:
var playing = request.playing;
if (playing == "true") {...
setInterval(sendInfo(), 500); means:
"Every 500 milliseconds, execute the value returned by sendInfo()."
Since you want to say:
"Every 500 milliseconds, execute the function named sendInfo."
chagne the above to:
setInterval(sendInfo, 500);
BTW, chrome.extension.sendRequest/onRequest are obsolete and should be replaced with chrome.runtime.sendMessage/onMessage instead.
Besides being obsolete, the former does not properly load an event page (a.k.a. non-persistent background-page) before sending the message, so this might be the cause of your problem.

How to toggle actions of a browser action?

I have created my first chrome extension which adds event handlers to all the anchor elements on the page on clicking. If the user clicks the icon second time the event handlers are reattached to the anchor elements and are executed twice.
What I need following
Click the browser action.
Add the events to the anchor elements
If possible give a visual cue in the browser action icon that the extension is active currently.
Clicking again on the extension should remove the event handlers and again shows the extension icon as disabled.
Is this possible?
Following is what I have tried till now.
manifest.json
{
"name":"NameExtension",
"version":"1.0",
"description":"Here goes the description",
"manifest_version":2,
"browser_action":{
"default_icon":"16x16.png"
},
"background":{
"scripts":["background.js"]
},
"permissions":[
"tabs","http://*/*","https://*/*"
]
}
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {file: "contentscript.js"});
});
contentscript.js
var all = document.getElementsByTagName('a');
for(var i=0; i<all.length;i++){
all[i].addEventListener('click',myHandler, false);
}
myHandler = function(event){
alert(event.target.innerText);
}
I would want the above handler to be toggled on anchors as the extension_browser_action is clicked and re-clicked. Also if the extension_browser-action_icon can give some visual feedback regarding the state.
I was able to do this with following in my background.js where contentscript adds the handlers and togglecontentscript removes them.
var x = false;
disableBrowserAction();
function disableBrowserAction(){
chrome.browserAction.setIcon({path:"inactive.png"});
chrome.tabs.executeScript(null, {file: "togglecontentscript.js"})
}
function enableBrowserAction(){
chrome.browserAction.setIcon({path:"active.png"});
chrome.tabs.executeScript(null, {file: "contentscript.js"});
}
function updateState(){
if(x==false){
x=true;
enableBrowserAction();
}else{
x=false;
disableBrowserAction();
}
}
chrome.browserAction.onClicked.addListener(updateState);

Chrome Extension: how to capture selected text and send to a web service

For the Google Chrome extension, I need to capture selected text in a web page and send to a web service. I'm stuck!
First I tried a bookmarklet, but Chrome on Mac seems to have some bookmarklet bugs so I decided to write an extension.
I use this code in my ext:
function getSelText(){
var txt = 'nothing';
if (window.getSelection){
txt = "1" + window.getSelection();
} else if (document.getSelection) {
txt = "2" + document.getSelection();
} else if (document.selection) {
txt = "3" + document.selection.createRange().text;
} else txt = "wtf";
return txt;
}
var selection = getSelText();
alert("selection = " + selection);
When I click on my extension icon, I get a "1". So I think the act of selecting outside the browser window is causing the text to not be seen by the browser as "selected" any more.
Just a theory....
thoughts?
You can do this by using Extensions Messaging. Basically, your "background page" will send the request to your service. For example, lets say you have a "popup" and once you click on it, it will do a "Google search" which is your service.
content_script.js
In your content script, we need to listen for a request coming from your extension, so that we send it the selected text:
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "getSelection")
sendResponse({data: window.getSelection().toString()});
else
sendResponse({}); // snub them.
});
background.html
Now in background page you can handle the popup onclick event so that we know we clicked on the popup. Once we clicked on it, the callback fires, and then we can send a request to the content script using "Messaging" to fetch the selected text.
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.sendRequest(tab.id, {method: "getSelection"}, function(response){
sendServiceRequest(response.data);
});
});
function sendServiceRequest(selectedText) {
var serviceCall = 'http://www.google.com/search?q=' + selectedText;
chrome.tabs.create({url: serviceCall});
}
As you have seen, I registered a listener in a content script to allow my extension to send and receive messages from it. Then once I received a message, I handle it by searching for Google.
Hopefully, you can use what I explained above and apply it to your scenario. I just have to warn you that the code written above is not tested, so their might be spelling, or syntax errors. But those can easily be found by looking at your Inspector :)
content script
document.addEventListener('mouseup',function(event)
{
var sel = window.getSelection().toString();
if(sel.length)
chrome.extension.sendRequest({'message':'setText','data': sel},function(response){})
})
Background Page
<script>
var seltext = null;
chrome.extension.onRequest.addListener(function(request, sender, sendResponse)
{
switch(request.message)
{
case 'setText':
window.seltext = request.data
break;
default:
sendResponse({data: 'Invalid arguments'});
break;
}
});
function savetext(info,tab)
{
var jax = new XMLHttpRequest();
jax.open("POST","http://localhost/text/");
jax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
jax.send("text="+seltext);
jax.onreadystatechange = function() { if(jax.readyState==4) { alert(jax.responseText); }}
}
var contexts = ["selection"];
for (var i = 0; i < contexts.length; i++)
{
var context = contexts[i];
chrome.contextMenus.create({"title": "Send to Server", "contexts":[context], "onclick": savetext});
}
</script>
manifest.json
{
"name": "Word Reminder",
"version": "1.0",
"description": "Word Reminder.",
"browser_action": {
"default_icon": "images/stick-man1.gif",
"popup":"popup.html"
},
"background_page": "background.html",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["js/myscript.js"]
}
],
"permissions": [
"http://*/*",
"https://*/*",
"contextMenus",
"tabs"
]
}
and here is the link where i have all in one extension to download.
after reading this i tried of my own and have published.
and here is the complete source
http://vikku.info/programming/chrome-extension/get-selected-text-send-to-web-server-in-chrome-extension-communicate-between-content-script-and-background-page.htm
Enjoy
Using a content_scripts is not a great solution as it injection to all documents including iframe-ads etc. I get an empty text selection from other pages than the one I expect half the times on messy web sites.
A better solution is to inject code into the selected tab only, as this is where your selected text lives anyhow. Example of jquery doc ready section:
$(document).ready(function() {
// set up an event listener that triggers when chrome.extension.sendRequest is fired.
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
// text selection is stored in request.selection
$('#text').val( request.selection );
});
// inject javascript into DOM of selected window and tab.
// injected code send a message (with selected text) back to the plugin using chrome.extension.sendRequest
chrome.tabs.executeScript(null, {code: "chrome.extension.sendRequest({selection: window.getSelection().toString() });"});
});
It is not clear from your code where it is. What I mean, is that if this code is either in popup html or background html then the results you are seeing are correct, nothing in those windows will be selected.
You will need to place this code in a content script so that it has access to the DOM of the page, and then when you click your browser action, you will need to send a message to the content script to fetch the current document selection.
You don't need a Google API for something as simple as this...
I'll use the Bing online service as an example. Note that the URL is set up to accept a parameter:
var WebService='http://www.bing.com/translator/?text=';
frameID.contentWindow.document.body.addEventListener('contextmenu',function(e){
T=frameID.contentWindow.getSelection().toString();
if(T!==''){e.preventDefault(); Open_New_Tab(WebService+encodeURIComponent(T)); return false;}
},false);
NB: The function "Open_New_Tab()" used above is an imaginary one that accepts the webservice URL with the encoded selected text as a parameter.
That's the idea basically.