Copy/Paste Not Working in Chrome Extension - google-chrome-extension

Following Copy/Paste code not working in Chrome Extension,
I need to write Chrome Extension that copy and paste data using clipboard.
I write following code in Backgroung.html page, but its not working.
function buttonClick(){
document.getElementById('initialText').select();
chrome.experimental.clipboard.executeCopy(1, function() {
alert("Copy");
document.getElementById('nameText').focus();
chrome.experimental.clipboard.executePaste(1, function() {
alert("Paste");
});
});
}

As of Chrome 13, clipboard access is no longer experimental.
The commands are now document.execCommand('paste'), document.execCommand('copy') and document.execCommand('cut').
However, permissions need to be added to your manifest: "clipboardRead" and "clipboardWrite".
Try implementing the above and see how you get on.

To eliminate the obvious; have you added the "experimental" permission to your manifest and are you using the latest dev build of Chrome as listed in the official documentation?
Otherwise, I'm not sure what may help you as I don't use the experimental API due to them not being usable in production. There is a workaround for copying without using the experimental API (using an input field and document.execCommand) but I'm not sure how to paste without it.
EDIT:
I've just noticed that experimental.clipboard is not longer listed on the experimental API page. It may be that this namespace has been deprecated/abandoned as can happen when using the experimental API. A simple test for this would be inserting;
console.log(typeof chrome.experimental.clipboard);
console.log(typeof chrome.experimental.clipboard.executeCopy);
console.log(typeof chrome.experimental.clipboard.executePaste);
Which should output the following the console for your background page;
> object
> function
> function

Related

How to navigate Edge extension local storage callback requirements

I'm trying to access the local storage data in Edge set by my options page, using my popup script. Is there a current, working example of this available?
I was using localStorage, but it would only update the popup if I reloaded the extension after saving changes in my options page. I want to make it easier on the user by allowing the popup to access it immediately after saving, without reloading. I found the browser.storage.local.get(), but documentation conflicts everywhere I look, and I can't find viable working examples.
I have used, per Edge documentation:
browser.storage.local.get("sample");
But it throws an error requiring a callback function. So then I used:
let sample = browser.storage.local.get("example");
sample.then(ifGood, ifBad);
I get an error regarding property "then".
Then I simply tried adding a callback to the action itself:
sample = browser.storage.local.get("example", callbackFunction);
function callbackFunction(data){
alert(data);
}
The end alert should display a string, but it just displays an empty Object. How do I access the data returned in the callback? I tried callbackFunction(this) as an argument in the get, but it throws an error about the syntax of the get.
I found a work-around using browser.runtime.reload() in the Options page when saving the changes. It still reloads the extension, but it does it without requiring the user to do it manually.
You should use this syntax:
browser.storage.local.get(propertyName | null, callbackFn)
where
callbackFn = function fn(resultObject) {...}
When you pass null you will get whole storage object.
Look for example 1 or example 2 in my Edge extension.

localstorage undefined on ie11 (windows 10) what is the solution? [duplicate]

The localStorage object in Internet Explorer 11 (Windows 7 build) contains string representations of certain functions instead of native calls as you would expect.
This only breaks with vanilla JavaScript and sites like JSFiddle have no problem with this code but I suspect it's because there are localStorage polyfills in place that correct it.
Take this HTML page code for example:
<!DOCTYPE html>
<script>
localStorage.setItem('test', '12345');
alert(localStorage.getItem('test'));
localStorage.clear();
</script>
This works perfectly well in all my installed browsers except for IE11. An error occurs on the first line 'SCRIPT5002: Function expected'.
Taking a look at what type the setItem function actually is in the IE developer tools console, states that it's a string...?
typeof localStorage.setItem === 'string' // true
Printing out the string for setItem displays the following:
"function() {
var result;
callBeforeHooks(hookSite, this, arguments);
try {
result = func.apply(this, arguments);
} catch (e) {
callExceptHooks(hookSite, this, arguments, e);
throw e;
} finally {
callAfterHooks(hookSite, this, arguments, result);
}
return result;
}"
Oddly enough, not all functions have been replaced with strings, for example, the corresponding getItem function is indeed a function and works as expected.
typeof localStorage.getItem === 'function' // true
Changing the document mode (emulation) to 10 or 9 still doesn't resolve the problem and both result in the same error. Changing the document mode to 8 gives the following error 'Object doesn't support this property or method' which is expected since IE8 doesn't support localStorage.
Is anyone else having the same issue with IE11 on Windows 7 where the localStorage object seems 'broken/corrupt'?
Turns out this is a problem in the base version of IE11 (11.0.9600.16428) for Windows 7 SP1.
After installing a patch to update to 11.0.9600.16476 (update version 11.0.2 - KB2898785) the issue gets resolved. Links to other versions of Windows (32-bit etc.) can be found at the bottom of the patch download page.
It's not just IE11's fault.
Probably WEINRE is injected into the page. It hooks into several system functions to provide Developer Tools functionality, but IE11 interprets assignments to the localStorage and sessionStorage properties wrong, and converts the hook functions into strings, as if they were the data that is going to be stored.
There's a comment in the apache/cordova-weinre repo which says:
#In IE we should not override standard storage functions because IE does it incorrectly - all values that set as
# storage properties (e.g. localStorage.setItem = function()[...]) are cast to String.
# That leads to "Function expected" exception when any of overridden function is called.
object[property] = hookedFunction unless navigator.userAgent.match(/MSIE/i) and (object is localStorage or object is sessionStorage)
Looks like it's either an old version of WEINRE being used, or this change hasn't been officially released (it's been there since 2013).
My localStorage returned undefined and I couldn't figure out why - until I realized that it was because I was running the HTML-page (with the localStorage script) directly from my computer (file:///C:/Users/...). When I accessed the page from a server/localhost instead it localStorage was indeed defined and worked.
In addition to the already excellent answers here, I'd like to add another observation. In my case, the NTFS permissions on the Windows %LOCALAPPDATA% directory structure were somehow broken.
To diagnose this issue. I created a new Windows account (profile), which worked fine with the localStorage,so then I painstakingly traversed the respective %LOCALAPPDATA%\Microsoft\Internet Explorer trees looking for discrepancies.
I found this gem:
C:\Users\User\AppData\Local\Microsoft>icacls "Internet Explorer"
Internet Explorer Everyone:(F)
I have NO idea how the permissions were set wide open!
Worse, all of the subdirectories has all permissions off. No wonder the DOMStore was inaccessible!
The working permissions from the other account were:
NT AUTHORITY\SYSTEM:(OI)(CI)(F)
BUILTIN\Administrators:(OI)(CI)(F)
my-pc\test:(OI)(CI)(F)
Which matched the permissions of the parent directory.
So, in a fit of laziness, I fixed the problem by having all directories "Internet Explorer" and under inherit the permissions. The RIGHT thing to do would be to manually apply each permission and not rely on the inherit function. But one thing to check is the NTFS permissions of %LOCALAPPDATA%\Microsoft\Internet Explorer if you experience this issue. If DOMStore has broken permissions, all attempts to access localStorage will be met with Access Denied.

Can js code in chrome extension detect that it's executed as content script?

I have a google chrome extension that shares some code between it's content script and background process / popup. If it some easy and straightforward way for this code to check if it's executed as content script or not? (message passing behavior differs).
I can include additional "marker" javascript in manifest or call some chrome fnction unavailable from content script and check for exceptions - but these methods looks awkward to be. Maybe it's some easy and clean way to make this check?
To check whether or not your script is running as a content script, check if it is not being executed on a chrome-extension scheme.
if (location.protocol == 'chrome-extension:') {
// Running in the extension's process
// Background-specific code (actually, it could also be a popup/options page)
} else {
// Content script code
}
If you further want to know if you're running in a background page, use chrome.extension.getBackgroundPage()=== window. If it's true, the code is running in the background. If not, you're running in the context of a popup / options page / ...
(If you want to detect if the code is running in the context of an extension, ie not in the context of a regular web page, check if chrome.extension exists.)
Explanation of revised answer
Previously, my answer suggested to check whether background-specific APIs such as chrome.tabs were defined. Since Chrome 27 / Opera 15, this approach comes with an unwanted side-effect: Even if you don't use the method, the following error is logged to the console (at most once per page load per API):
chrome.tabs is not available: You do not have permission to access this API. Ensure that the required permission or manifest property is included in your manifest.json.
This doesn't affect your code (!!chrome.tabs will still be false), but users (developers) may get annoyed, and uninstall your extension.
The function chrome.extension.getBackgroundPage is not defined at all in content scripts, so alone it can be used to detect whether the code is running in a content script:
if (chrome.extension.getBackgroundPage) {
// background page, options page, popup, etc
} else {
// content script
}
There are more robust ways to detect each context separately in a module I wrote
function runningScript() {
// This function will return the currently running script of a Chrome extension
if (location.protocol == 'chrome-extension:') {
if (location.pathname == "/_generated_background_page.html")
return "background";
else
return location.pathname; // Will return "/popup.html" if that is the name of your popup
}
else
return "content";
}

Developer documentation for previous releases of the Chromium\Google Chrome [duplicate]

I love what chrome offers me through its extension API.
But I always find myself lost in the jungle of what API is supported by which chrome version and when did the last chrome.experimental feature make it into the supported extensions.
The Chrome extension page gives me a nice overview what is supported, but without mentioning since what version. The same is true for the experimental API overview. Is that specific API still experimental or is it already supported in canary, for example.
If I try a sample from the chrome Samples website I usually have to change some API calls from chrome.experimental.foo to chrome.foo or find out that it is not supported at all. (What happened to chrome.experimental.alarm?) That usually means to just use the trial and error approach to eliminate all errors, until the sample works.
tldr;
So, I'm wondering is there an overview page which tells me since what version, what API is supported or when it was decided to drop an experimental API. And if there is no such page, what is the recommended way or your personal approach to deal with this situation?
On this page, the process of generating the official documentation (automatically from the Chrome repository) is described. On the same page, you can also read how to retrieve documentation for older branches. Note that the documentation is somehow incomplete: Deprecated APIs are included immediately, although they're still existent (such as onRequest).
What's New in Extensions is a brief list of API changes and updates (excluding most of the experimental APIs). It has to be manually edited, so it's not always up-to-date. For example, the current stable version is 20, but the page's last entry is 19.
If you really need a single page containing all API changes, the following approach can be used:
First, install all Chrome versions. This is not time consuming when done automatically: I've written a script which automates the installation of Chrome, which duplicates a previous profile: see this answer.
Testing for the existence of the feature:
Write a manifest file which includes all permissions (unrecognised permissions are always ignored).
Chrome 18+: Duplicate the extension with manifest version 1 and 2. Some APIs are disabled in manifest version 1 (example).
Testing whether a feature is implemented and behaving as expected is very time-consuming. For this reason, you'd better test for the existence of an API.
A reasonable manner to do this is to recursively loop through the properties of chrome, and log the results (displayed to user / posted to a server).
The process of testing. Use one of the following methods:
Use a single Chrome profile, and start testing at the lowest version.
Use a separate profile for each Chrome version, so that you can test multiple Chrome versions side-by-side.
Post-processing: Interpret the results.
Example code to get information:
/**
* Returns a JSON-serializable object which shows all defined methods
* #param root Root, eg. chrome
* #param results Object, the result will look like {tabs:{get:'function'}}
*/
function getInfo(root, results) {
if (root == null) return results;
var keys = Object.keys(root), i, key;
results = results || {};
for (i=0; i<keys.length; i++) {
key = keys[i];
switch (typeof root[key]) {
case "function":
results[key] = 'function';
break;
case "object":
if (subtree instanceof Array) break; // Exclude arrays
var subtree = results[key] = {};
getInfo(root[key], subtree); // Recursion
break;
default:
/* Do you really want to know about primitives?
* ( Such as chrome.windows.WINDOW_ID_NONE ) */
}
}
return results;
}
/* Example: Get data, so that it can be saved for later use */
var dataToPostForLaterComparision = JSON.stringify(getInfo(chrome, {}));
// ...

How to use the experimental offscreenTab API?

I've been searching for examples and reference and have come up with nothing. I found a note in offscreenTab source code mentioning it cannot be instantiated from a background page (it doesn't have a tab for the offscreenTab to relate to). Elsewhere I found mention that popup also has no tie to a tab.
How do you successfully create an offscreenTab in a Chrome extension?
According to the documentation, offscreenTabs.create won't function in a background page. Although not explicitly mentioned, the API cannot be used in a Content script either. Through a simple test, it seems that the popup has the same limitation as a background page.
The only leftover option is a tab which runs in the context of a Chrome extension. The easiest way to do that is by using the following code in the background/popup:
chrome.tabs.create({url: chrome.extension.getURL('ost.htm'), active:false});
// active:false, so that the window do not jump to the front
ost.htm is a helper page, which creates the tab:
chrome.experimental.offscreenTabs.create({url: '...'}, function(offscreenTab) {
// Do something with offscreenTab.id !
});
To change the URL, use chrome.experimental.offscreenTabs.update.
offscreenTab.id is a tabId, which ought to be used with the chrome.tabs API. However, at least in Chrome 20.0.1130.1, this is not the case. All methods of the tabs API do not recognise the returned tabID.
A work-around is to inject a content script using a manifest file, eg:
{"content_scripts": {"js":["contentscript.js"], "matches":["<all_urls>"]}}
// contentscript.js:
chrome.extension.sendMessage({ .. any request .. }, function(response) {
// Do something with response.
});
Appendum to the background page:
chrome.extension.onMessage.addListener(function(message, sender, sendResponse) {
// Instead of checking for index == -1, you can also see if the ID matches
// the ID of a previously created offscreenTab
if (sender.tab && sender.tab.index === -1) {
// index is negative if the tab is invisible
// ... do something (logic) ...
sendResponse( /* .. some response .. */ );
}
});
With content scripts, you've got full access to a page's DOM. But not to the global object. You'll have to inject scripts (see this answer) if you want to run code in the context of the page.
Another API which might be useful is the chrome.webRequest API. It can be used to modify headers/abort/redirect requests. Note: It cannot be used to read or modify the response.
Currently, the offscreenTabs API is experimental. To play with it, you have to enable the experimental APIs via chrome://flags, and add "permissions":["experimental"] to your manifest file. Once it's not experimental any more, use "permissions":["offscreenTabs"].

Resources