Code not executing? - google-chrome-extension

I have a simple extension for Google Chrome that should collect data from you with a variable and prompt, and then should print what you inputted with document.write(variable_name);
Upon entering the code into the prompt, it does not print it.
I know the code is right, it works if I paste it into console, just not as an extension
How do I fix this?
var variable_name = prompt("Enter something");
document.write(variable_name);

You haven't provided anywhere near enough context, but I'm going to toss out a theory here:
You're probably running that code in your extension's background page. If that's the case, you'd have an entry something like this in your manifest.json:
"background": {
"scripts": ["background.js"]
}
Background code is executed on its own thread, with its own DOM. It can not interact with the current page. What you need is a content script. You'll make an entry in manifest.json that describes what pages you want it to be injected into. If you'd like to inject your code into every page, you can use "matches": ["<all_urls>"]. Otherwise, see this page for help with creating a pattern (of set of patterns) to match the page(s) you want.
...or maybe I'm completely wrong, and you're already using a content script. If that's the case, please provide your entire manifest.json and any other code that's used in your extension.

Related

ExecuteScript in a random tab that is not part of the chrome extension send result back to background javascript

I would like to check the html of an element of a
chrome.tabs.executeScript(tab_id,{code: 'sendRequestToBackground(document.getElementById('important_val').innerHTML); '},
function(){
});
I want to be able to get this value from my background script, I saw a lot of examples with chrome.extension.sendRequest and chrome.extension.onRequest.addListener because all the examples is for working from the extension popup.html to background script and vice-versa.
But I open a brand new tab, change the URL, and I want to get a value of a field that (which btw is generated via Javascript) belongs to this random tab.
Is it possible to do that?
Thanks!
If you want to inject your code to a random tab, do this:
Be sure to have permissions to "tabs" and "<all_urls>" in your manifest.json
Get all tabs using chrome.tabs.query
Pick random tab using Math.random()
Inject the code using chrome.tabs.executeScript
In the incjected code call chrome.extension.sendRequest
On the background page receive the message using chrome.extension.onRequest

Chrome Content Scripts not loading JS

I'm trying to work on a Chrome browser extension which does fun things on a contextmenu. The problem is, I can't get the JS files to load within the manifest.json content_scripts.
I don't receive an error, the files simply do not load.
The scripts are good, if I put them in my background page, they fire fine through that background page. The downside of that is it's restricted to only the background page.
{
"name": "Mini",
"description": "Mini",
"permissions": ["contextMenus","management","contentSettings","tabs","http://*/*","https://*/*","editable"],
"version": "0.1",
"manifest_version": 1,
"background_page": "mini.html",
"icons" : {"16" : "mini.png"},
"contexts" : ["link","tab","page"],
"content_scripts": [{"matches":["<all_urls>"],"js":["jquery172min.js","mini.js"]}]
}
I've tried all forms of matches, including "http://\*/\*", "https://\*/\*", "\*://\*/\*"
I've tried whitespaces, no whitespaces. I'm drawing a blank here.
Any help would be appreciated.
$(document).ready(function () {
alert("page is ready");
},true);
My apologies for that. This is a copy of the javascript/Jquery I'm using to test whether the extension has loaded or not. It's just a simple alert.
Content scripts cannot use the chrome.contextMenus API (in fact, these can only use some of the chrome.extension methods).
It's possible to apply match patterns to individual menu items, via chrome.contextMenus.create({title: 'Test', documentUrlPatterns: 'http://*/*'});.
Created menu items can also be modified (chrome.contextMenus.update) and removed (chrome.contextMenus.remove).
To communicate between a Content script and the background page, see Message passing.

Chrome extension: Copy text

I have a simple chrome extension where I'd like to click an image and copy the href of the link next to it. I have everything in place, but the copy will not work for the life of me. I have the following premissions in my manifest:
"permissions": [
"clipboardRead",
"clipboardWrite"
]
I then create an input with id "copyInp" and use the following function to copy to clipboard (tried to be as deliberate as possible here, so it's not the most compact):
function copyLinkToClipboard( link ) {
$("#copyInp").val(link);
var inp = document.getElementById("copyInp");
inp.focus();
inp.select();
document.execCommand('copy');
};
After this runs, I get nothing new in my clipboard when I ctrl+v. Any ideas as to what's going wrong here? The input definitely has the text I want in it, and I have the permission in the manifest. Any help would be greatly appreciated...
After a bit more digging I discovered I needed to use a background page. Apparently this is the only thing you can call document.execCommand on. So the fix is to create a background.html with the copy function and the input in it, add a listener like so:
chrome.extension.onRequest.addListener(function(obj) {
copyLinkToClipboard( obj.link );
});
and then use sendRequest to pass the text you want copied to the background page:
chrome.extension.sendRequest({link: linkText});
and don't forget to add the background page in the manifest
"background_page": "background.html",
voila. text copied to clipboard. would LOVE an easier way to do this (if security is the issue then why not make an api for extensions? or rather, why scrap the experimental api only to force us to do this stupid workaround?) but oh well, this will suffice for the time being

Tracking Chrome extension events in Analytics

Google Chrome Extension documentation has some good information here:
http://code.google.com/chrome/extensions/tut_analytics.html
I put the analytics tracking code in my background.html file.
However I tried putting the _gaq.push call inside a script that runs on the page and got an error saying that the variable _gaq is not defined.
So I have to put onclick events in every element on the page I want to track and from there, call a function in background.html? Is there a better way to track events?
You can do this with chrome.extension.sendRequest in the content script and chrome.extension.onRequest.addListener in the background.html page. See here for more details: http://code.google.com/chrome/extensions/messaging.html. Also be sure your manifest.json is correct; I ran into problems when I had a hyphen character instead of an underscore.

Function not defined creating a Chrome Extension Content Script

I'm writing a Chrome content script and when I inject this in the DOM:
"<a href='#' onclick='alert(\"Hi!\");return false;'>Hi</a>"
it works fine (the alert pops up when I click it), however if I create a function for the alert, it will say function undefined. Ex:
"<a href='#' onclick='alertPlease(\"Hi!\");return false;'>Hi</a>"
function alertPlease(x){
alert(x);
}
All my code is the same content script js file.
Do I have to place whatever code that can be used after loading in another js file in the background? I tried adding a background page with the 'alertPlease();' function, but that didn't work either.
Any hint will be greatly appreciated!
Thanks!
Content scripts run in an "isolated world." The webpage and content scripts can't see each other's JavaScript variables (although they can see the same DOM). When you add an onclick attribute within the DOM, the handler is created on the webpage's world, not your extension's world, so that code can't access the other function you defined. Instead of using an onclick handler, you should define your event listener in pure Javascript and then use addEventListener to attach it.
Isolated worlds are a feature to improve security and stability. Things are similar if you're developing within the Greasemonkey sandbox in Firefox.
Doing one of these today with manifest version 3, I learned:
I can't append a button to the page and use
<button type="button" onclick="myContentScriptFunction();">Call CS Function</div>
But, in the content script, I can do vanilla
let loadButton = document.createElement('button');
loadButton.innerText = 'Call CS Function';
loadButton.addEventListener('click', myContentScriptFunction);
document.querySelector('body').append(loadButton);
or jQuery
let loadButton = $("<button type="button">Call CS Function</button>")
loadButton.on("click", myContentScriptFunction)
$("body").append(loadButton);
And both worked as expected with all code in the content script
Info Source: Chrome Extension Samples Example
Specify any scripts in the manifest.json file under "content_scripts"
{
"name": "My Extension",
"content_scripts": [{
"matches": ["<all_urls>"],
"css": ["style.css"],
"js": ["jquery-1.5.js", "script.js"]
}]
}

Resources