Javascript Copy Clipboard function which works perfectly on all latest browsers - javascript

I have got below cocpy clipboard function which works perfectly on latest Internet Explorer as well as Latest Firefox.
function copyToClipboardCrossbrowser(s)
{
//s = document.getElementById(s).value;
if( window.clipboardData && clipboardData.setData )
{
clipboardData.setData("Text", s);
}
else
{
// You have to sign the code to enable this or allow the action in about:config by changing
//user_pref("signed.applets.codebase_principal_support", true);
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
var clip = Components.classes["#mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
if (!clip) return;
// create a transferable
var trans = Components.classes["#mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
if (!trans) return;
// specify the data we wish to handle. Plaintext in this case.
trans.addDataFlavor('text/unicode');
// To get the data from the transferable we need two new objects
var str = new Object();
var len = new Object();
var str = Components.classes["#mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
str.data= s;
trans.setTransferData("text/unicode",str, str.data.length * 2);
var clipid=Components.interfaces.nsIClipboard;
if (!clip) return false;
clip.setData(trans,null,clipid.kGlobalClipboard);
}
}
Can you please suggest what changes I need to do in above function so that works perfectly on safari as well as opera.
I know there is way if we install shockwave on these browsers using flash to get copied data. I just don't want to go for flash solution.
Thanks.
Best Regards,
Manoj

Related

Is there anyway to change the path of a blob from URL.createObjectURL

I am using GMS1.4 HTML5 module and i'm currently trying to import sprite images to it. The issue is i don't want to save it in the local directory and since there is a built in function that allows the sprite to be added from a URL i was thinking of just using a blob to get the job done so the temp sprite is erased from memory after the user is done with the game.
The problem is 1.4 is sandboxed so all url links and references seems to point to the Local storage. instead of
blob:http://mysite.co/85cad96e-e44e-a1f9-db97a96ed3fe
it'll preapped like this
http://mysite.co/html5game/blob:http://mysite/85cad96e-e44e-a1f9-db97a96ed3fe
Im only assuming its due to the sandbox nature of GMS and there does not seem to be a way to turn it off. my next idea is since it wants to be stubborn about using the sandbox directory, was to just create the blob within that folder. Is it possible to create at path and URL.createObjectURL?
You could adapt an approach based on what I did for "Allow Data URI" to also allow blob URIs. Excerpt follows,
GML:
#define gmcallback_AllowDataURI
if (AllowDataURI()) {
AllowDataURI(sprite_add("", 1, 0, 0, 0, 0));
}
JS:
function AllowDataURI() {
var p0 = "\\s*\\(\\s*";
var p1 = "\\s*\\)\\s*";
var eq = "\\s*=\\s*";
var id = "\\w+";
//
var init_js = window.gml_Script_gmcallback_AllowDataURI.toString();
var sprite_add_js = window[
/\bAllowDataURI\s*\(\s*(\w+)/.exec(init_js)[1] // AllowDataURI(sprite_add(...
].toString();
var sprite_add_url = /function\s*\w*\s*\((\w+)/g.exec(sprite_add_js)[1];
var sprite_add_url2 = new RegExp(
"("+id+")"+eq+sprite_add_url+"\\b", // `sprite_add_url2 = sprite_add_url`
"g").exec(sprite_add_js);
sprite_add_url2 = sprite_add_url2 ? sprite_add_url2[1] : sprite_add_url;
//
var image_add_js = window[new RegExp(
id+eq+"("+id+")"+p0+sprite_add_url2+p1, // `_ = image_add(sprite_add_url2)`
"g").exec(sprite_add_js)[1]].toString();
var image_add_url = /function\s*\w*\s*\((\w+)/g.exec(image_add_js)[1];
//
var url_proc = new RegExp(
id+eq+"("+id+")"+p0+image_add_url+p1, // `_ = url_proc(image_add_url)`
"g").exec(image_add_js)[1];
window[url_proc] = (function() {
var f = window[url_proc];
return function(url) {
if (url.substring(0, 5) == "data:") return url;
if (url.substring(0, 5) == "blob:") return url; // new!
return f.apply(this, arguments);
};
})();
//
return false;
}

Object doesn't support property or method 'getAll'

I am trying to implement service workers into my application, which I have managed to do in Chrome, Firefox and Safari but not completely in IE. So far I am able to create an object store and add data to it but when I call getAll() I get the following error:
SCRIPT438: Object doesn't support property or method 'getAll'
This is the code I am trying to run:
var docDB = indexedDB.open("docDB", 1);
docDB.onsuccess = function(event) {
var db = docDB.result;
var tx = db.transaction("documents", "readwrite");
var docStore = tx.objectStore("documents");
var docStoreRequest = docStore.getAll();
docStoreRequest.onsuccess = function(event) {
var rowHTML = '';
$.each( docStoreRequest.result, function( index, value ){
var id = $(this)[0].id;
});
};
Neither IE nor Edge support all of the IndexedDB spec. One of the missing things is getAll. Fortunately, there is a polyfill you can use.

IE11 not recognizing .loadXML()

Working on some xml data and my function works in all browsers except for IE10 and up.
Is there something else I can use instead of .loadXML(data)
Here is part of the transform function. it breaks at x.loadXML(data)
$.transform = function(o) {
var createXmlObj = function(data) {
if($.browser.msie) {
var x = $("<xml>")[0];
x.loadXML(data);
return x;
} else {
var parser = new DOMParser();
return parser.parseFromString(data,"text/xml");
}
};
add your page to Internet Explorer's Compatibility View Settings. You won't believe the types of issues that this fixes.

copy to clipboard is not working in firefox 25

how can I implement "Clipboard" functionality in Firefox V25 . Even though I've changed in "about:config" the "dom.event.clipboardevents.enabled" to true as well as "clipboard.autocopy" to true , then also it's not working . Kindly give me a solution for this problem.
I used this piece of code for clipboard operation:
function copyToClipboardCrossbrowser(s) {
s = document.getElementById(s).value;
if( window.clipboardData && clipboardData.setData )
{
clipboardData.setData("Text", s);
}
else{
// You have to sign the code to enable this or allow the action in about:config by changing
//user_pref("signed.applets.codebase_principal_support", true);
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
var clip = Components.classes["#mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
if (!clip) return;
// create a transferable
var trans = Components.classes["#mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
if (!trans) return;
// specify the data we wish to handle. Plaintext in this case.
trans.addDataFlavor('text/unicode');
// To get the data from the transferable we need two new objects
var str = new Object();
var len = new Object();
var str = Components.classes["#mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
str.data= s;
trans.setTransferData("text/unicode",str, str.data.length * 2);
var clipid=Components.interfaces.nsIClipboard;
if (!clip) return false;
clip.setData(trans,null,clipid.kGlobalClipboard);
}
}
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect')
do not work in current version of firefox because of security considarations - seaching for a solution myself!

How do I change the flashvars using the ContentScript of a Chrome Extension?

I want to create a chrome extension to help me debug my swf, and I'd like the extension to be able to change some of the flashvars while keeping others untouched.
I can't imagine this is a new or unique problem, so before I reinvent the wheel, I'm asking if anyone here has examples of it being done, or how to do it.
I've tried searching, but my googlefu seems to be off.
My use case is as follows. I have a Google Chrome extension which has a few drop down menus with possible flash var values. I want the change the values in the drop down, and then reload the swf with these new flashvars, but without changing flashvars which are not in my drop down menus.
I'm able to easily inject a new swf on the page with the values from my dropdown menus, however I'd like to be able to reload, rather than recreate, the swf.
I have tried using Jquery to pull all the flash vars like this:
var flashVars = $("param[name=flashvars]", gameSwfContainer).val();
However, I'm having a hard time changing or replacing just a couple of the values, and then injecting them back into the object. (Regex might be helpful here unless there is a better way?)
Thanks for your help.
Currently, I am trying to do the following, but I'm not sure if it's the right direction.
ContentScript.js
//Setup
var swfVersionStr = "10.1.0";
var xiSwfUrlStr = "playerProductInstall.swf";
var params = {};
params.quality = "high";
params.bgcolor = "#000000";
params.allowscriptaccess = "always";
params.allowfullscreen = "true";
var attributes = {};
attributes.id = "game_swf_con";
attributes.name = "game_swf_con";
attributes.class = "game_swf_con";
attributes.align = "middle";
var InjectedFlashvars = {
"run_locally": "true",
//.. some other flash vars that I won't be changing with my extension
"swf_object_name":"game_swf"
};
// Injection code called when correct page and div detected;
var injectScriptText = function(text)
{
loopThroughLocalStorage();
swfobject.embedSWF(
swfName, "game_swf_con",
"760", "625",
swfVersionStr, xiSwfUrlStr,
InjectedFlashvars, params, attributes);
swfobject.createCSS("#game_swf_con", "display:block;text-align:left;");
};
function loopThroughLocalStorage()
{
for(key in localStorage){
try{
var optionArray = JSON.parse(localStorage[key]);
var option = returnSelectedFlashVar(optionArray);
var value = option.value ? option.value : "";
InjectedFlashvars[key] = value;
} catch(err){}
}
}
function returnSelectedFlashVar(optionArray){
for(var i= 0; i < optionArray.length;i++)
{
if(optionArray[i].selected == true)
{
return optionArray[i];
}
}
}
Overall, I currently have contentscript.js, background.js, options.js, options.html, popup.html and popup.js The code above so far only exists in contentscript.js
Had a little trouble deciding what you actually wanted.
But if its manipulating the values in the flashvar maybe this will help...
queryToObject = function(queryString) {
var jsonObj = {};
var e, a = /\+/g,
r = /([^&=]+)=?([^&]*)/g,
d = function(s) {
return decodeURIComponent(s.replace(a, " "));
};
while(e = r.exec(queryString)) {
jsonObj[d(e[1])] = d(e[2]);
}
return jsonObj;
}
objectToQuery = function(object) {
var keys = Object.keys(object),
key;
var value, query = '';
for(var i = 0; i < keys.length; i++) {
key = keys[i];
value = object[key];
query += (query.length > 0 ? '&' : '') + key + '=' + encodeURIComponent(value);
}
return query;
}
// this is what a flashvar value looks like according to this page...http://www.mediacollege.com/adobe/flash/actionscript/flashvars.html
var testQuery = 'myvar1=value1&myvar2=value2&myvar3=a+space';
var testObject = queryToObject(testQuery);
console.debug(testObject);
testQuery = objectToQuery(testObject);
console.debug(testQuery);
testObject.myvar0 = 'bleh';
delete testObject.myvar2;
console.debug(objectToQuery(testObject));
And if your using localStorage in a content script then be aware that the storage will be held in the context of the page.
Try looking at chrome.storage instead.
EDIT : Answer to comments
This looks correct, but how do I "reload" the object so that those new flashvars are the ones that are used by the swf?
Ive never used swfObject (havent done any flash stuff in like 5 years) but had a look and it looks like you can just rerun the swfobject.embedSWF with the new flashVars and it will replace the old object with the new one. Which is fine if your replacing one that you added yourself as you can supply all of the details, if your replacing something put there by someone else you could clone the object, change some stuff and replace the original with the clone. Cloning will not clone any events attached to the element but I dont think thats a problem in your case. Here's an example (which I couldnt test as I couldnt find any simple sample swf that just prints the flashvars)....
var target = document.querySelector('#game_swf_con');
// Cloning the element will not clone any event listners attached to this element, but I dont think that's a prob for you
var clone = target.cloneNode(true);
var flashvarsAttribute = clone.querySelector('param[name=FlashVars]');
if (flashvarsAttribute) {
var flashvars = flashvarsAttribute.value;
flashvars = queryToObject(flashvars);
// add a new value
flashvars.newValue = "something";
// update the clone with the new FlashVars
flashvarsAttribute.value = objectToQuery(flashvars);
// replace the original object with the clone
target.parentNode.replaceChild(clone, target);
}​
Sources:
a) Content Scripts
b) Background Pages
c) Message Passing
d) tabs
e) Browser Action
f) API()'s
Assuming a html page containing following code
<embed src="uploadify.swf" quality="high" bgcolor="#ffffff" width="550"
height="400" name="myFlashMovie" FlashVars="myVariable=Hello%20World&mySecondVariable=Goodbye"
align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash"
pluginspage="http://www.adobe.com/go/getflash" />
I try to get following get height of embed object and change it.
Sample Demonstration
manifest.json
{
"name":"Flash Vars",
"description":"This demonstrates Flash Vars",
"manifest_version":2,
"version":"1",
"permissions":["<all_urls>"],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["myscript.js"]
}
]
}
myscript.js
// Fetches Current Width
width = document.querySelector("embed[flashvars]:not([flashvars=''])").width;
console.log("Width is " + width);
// Passing width to background.js
chrome.extension.sendMessage(width);
//Performing some trivial calcualtions
width = width + 10;
//Modifying parameters
document.querySelector("embed[flashvars]:not([flashvars=''])").width = width;
background.js
//Event Handler for catching messages from content script(s)
chrome.extension.onMessage.addListener(
function (message, sender, sendResponse) {
console.log("Width recieved is " + message);
});
Let me know if you need more information.

Categories

Resources