I'm about to create my first Chrome extension (it's a Popup), it'll POST data to a server.
Thought it would be easy, but I get stuck.
in manifest.json I set permissions for "http://mypage[dot]com/" and also "http://mypage[dot]com/*" so that I can access the "mypage[dot]com/api" where the data has to be sent to.
And so my popup.html looks like:
<!doctype html>
<html lang="en">
<meta charset="UTF-8">
<title>myExtension</title>
</head>
<body>
<form name="myform">
<input type="text" name="myText" id="myText"/>
<input type="submit" name="senden"/>
</form>
</body>
<script src="jquery-1.8.2.min.js"></script>
<script src="popup.js"></script>
</html>
And so my popup.js looks like:
document.forms["myForm"].addEventListener("submit", sendRequest)
function sendRequest() {
var myVar= $('#mytext').val();
var myrequest= $.ajax({
type: 'POST',
url: 'http://mypage.com/api/',
data: {screen_name: 'myname', api_key: 'myKey', var1: myVar},
success: function(data, textStatus){
alert('request successful');
},
error: function(xhr, textStatus, errorThrown){
alert(xhr); alert(textstatus); alert(errorThrown);
}
});
}
Now, when I hit the submit-button it'll give me only these three alerts, the first one says: [object Object], the second one: error and the third one is only empty.
I tried to solve this problem but I dont know where the error is. Also I read about some background.html and content_script.js but I dont know what I have to do with them and some extensions, I found in the internet, only contain the popup.html and popup.js and they work as fine as they should do (e.g. the domai.nr-extension).
So I'd very happy about some explanations what I have to use and to do to post data correctly within a popup extension.
first, you close the head tag but dont open it
try to give your form an id like
<form id="myform">
then i would simplify the js code like this
$('#myform').submit(function(){
var myVar= $('#mytext').val();
$.ajax({
url: "http://mypage.com/api/",
type: "POST",
data: {screen_name: 'myname', api_key: 'myKey', var1: myVar},
success: function(data, textStatus){
alert('request successful');
},
error: function(xhr, textStatus, errorThrown){
alert(xhr); alert(textstatus); alert(errorThrown);
}
});
});
Issue
If you want to make a Cross-Origin ajax call, you need to request appropriate permissions.
Debugging
Better way to debug variables than alert() is console.log(). To see the output of this method you need to open a console. To open a console for a popup: open a popup, right click on it and choose 'inspect element'. When Developer Tools will open, navigate to 'Console' tab. You will get much more information from console.log(xhr) than from alert(xhr). In addition all permission warnings, invalid syntax warnings etc. are printed out on console making it easy to find a bug.
AJAX from popup
Sending a POST request from a popup has a one week point: when popup is closed (and it's closed very easily - when user clicks something outside the popup) the request is canceled. And here comes the background page you mentioned. Background page works in (surprise, surprise) background and can't be easily closed. Your popup should communicate with background page and ask it to make an ajax call. If you do that, background page will perform AJAX call even though popup may be already closed.
Check your function in http://mypage.com/api/.
test it by write simple response like that:
function nameOfFunciton(){
echo "test";
}
If you see "request successful" alert, thus the problem exist in your code.
Related
In the tutorial for migrating a Google Chrome Extension to Manifest Version 2, I am directed to Remove inline event handlers (like onclick, etc) from the HTML code, move them into an external JS file and use addEventListener() instead.
OK, I currently have a background.html page that looks like this…
<html>
<script type="text/javascript">
// Lots of script code here, snipped
…
</script>
<body onload="checkInMyNPAPIPlugin('pluginId');">
<object type="application/x-mynpapiplugin" id="pluginId">
</body>
</html>
Following another directive, I've moved that Lots of script code into a separate .js file, and following this directive, I need to remove the onload= from the body tag, and instead cal addEventListener() in my script code. I've tried several approaches, but am apparently guessing wrong. What will that code look like? In particular, upon what object do I invoke addEventListener()?
Thanks!
I normally use this for body onload event...
document.addEventListener('DOMContentLoaded', function () {
// My code here.. ( Your code here )
});
For somethings it is working.. but really, I think we should use..
window.addEventListener('load', function () {
document.getElementById("#Our_DOM_Element").addEventListener('change - or - click..', function(){
// code..
});
});
I want to send an array from my content script to the background page, so that it can be stored and called upon later from the popup using chrome.extension.getBackgroundPage().
At the moment, my background page looks like this (based on an example from the developer website).
<html>
<head>
<script>
function onRequest(request, sender, sendResponse) {
chrome.pageAction.show(sender.tab.id);
sendResponse({});
};
chrome.extension.onRequest.addListener(onRequest);
</script>
</head>
</html>
My content script performs a few simple regexes, and if it finds a match responds with:
chrome.extension.sendRequest({}, function(response) {});
What I would like to do is send an array created by the content script back to the background page. I'm somewhat stumped as to how to go about this. Do I need to create a second request, or can I send the array along with the response above.
Thank you all for your help. This is my first time posting here, though I've long benefited from the questions and answers posted by others :)
Assuming your array of matches is called matches, your content script could use something like:
chrome.extension.sendRequest({matches: matches}, function(response) {});
Then in your background page, you can extract the matches array from the request:
function onRequest(request, sender, sendResponse) {
var matches = request.matches;
// do stuff with the matches array here
sendResponse({});
};
Generally, whatever data you put into the request argument of chrome.extension.sendRequest will be passed to your onRequest function. See the extension documentation about message passing for more details.
I'm trying to close the Options page of the extension.
I have a Cancel button and I'm using this code:
chrome.tabs.getCurrent(null, function(tab) {
chrome.tabs.remove(tab.id, function() {});
});
When I'm trying to use it, it always gives this error:
Uncaught TypeError: Cannot call method 'getCurrent' of undefined
What's wrong with the code?
It works for me with one little fix:
chrome.tabs.getCurrent(function(tab) {
chrome.tabs.remove(tab.id, function() { });
});
Just make sure you're really running this code in options page of your extension and not just some HTML page, because chrome.tabs API is available only for extensions.
Most likely you're running your code from a content script, where chrome.tabs is undefined. If this is the case, you can instead send a message to the background page and have the background page (which has access to chrome.tabs) make the call.
Note that from a background page, you would use chrome.tabs.getSelected since getCurrent will return undefined.
In the options page, you can just do:
window.close()
If you wanted to use chrome.tabs.getCurrent, do you have tabs defined in the permissions section within the manifest?
I have time to continue my extension after a very long time. I checked the documentation again. So it was a inline script, that I had probably blocked with Content Security Policy in the manifest, because I hadn't read the documentation precisely.
Now Chrome blocks inline scripts by default, so I'll have to fix it anyway.
Only this worked for me:
chrome.tabs.query({ active: true }, function(tabs) {
chrome.tabs.remove(tabs[0].id);
});
I'm in the process of making a Google Chrome extension, and encountered a problem.
I'm trying to upload and search through the DOM inside the popup.html.
Here is how I get the current tab (I found the script somewhere, credit doesn't belong to me):
chrome.windows.getCurrent(function(w) {
chrome.tabs.getSelected(w.id,function (response){
)};
My problem is this: I need to traverse through the DOM of the response. When trying to do so manually, I couldn't, as the response variable was now undefined for some reason, so using the Console isn't an option.
When trying to alert the response in the html file, it came as a object. Then, I tried to navigate through the response as if it has been the 'document' object, but no luck either.
Any help will be appreciated greatly.
You can get the selected tab for your popup by passing null as the window id to getSelected. () In your popup you can listen for extension events and execute a script to push the content to your popup:
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if (request.action == "content")
{
console.log('content is ' + request.content.length + ' bytes');
}
});
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.executeScript(tab.id, { file: 'scripts/SendContent.js' } );
});
And finally the content script... I have it as "scripts/SendContent.js" in my extension folder, but the script is simple enough you could execute it by putting the code in the code property instead of the name in the file property of the object you pass to executeScript:
console.log('SendContent.js');
chrome.extension.sendRequest( {
action: "content",
host: document.location.hostname,
content: document.body.innerHTML
}, function(response) { }
);
Result:
POPUP: content is 67533 bytes
If you're having trouble, use console.log() and right-click on your page or browser action to inspect it and read your messages on the console (or debug your script from there).
I believe popups are sandboxed the same way that background pages are, so you'll need to use a content script to access the page DOM.
You can inject a content script with chrome.tabs.executeScript, handle your DOM traversal in the content script, then pass back the information you need from the content script to the popup using the message passing API.
I can try to elaborate on this if you give more information about the problem you're trying to solve.
Jquery auto refresh is using up a LOT of browser memory. Is there a way to stop this. I had a 2 div refreshing every 3 seconds but I moved it up to 9 and 15 seconds, It helped a little bit the longer the window stays open on my site the more memory it takes until finally the browser crashes.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" ></script>
<script>
var auto_refresh = setInterval(
function ()
{
$('#details2').load('links2.php').fadeIn("slow");
}, 15000); // refresh every 10000 milliseconds</script>
You could try to skip the load() and use $.ajax instead. I know load(); is an ajax request but I seem to recall it fetches the whole script. Try requesting a script, do your database calculations and return the data as json. I assume you're sending complete html with the data from the database request. Try this with json instead.
You'll get the data as an object, like this for example.
{"variable":"foo"}
Then you can fetch the data with a simple each statement.
$.ajax({
url: "links2.php",
type: "POST",
dataType: "json",
success: function(data){
// data here is returned as objects since it's json
$.each(data, function(key, value) {
$("#details2").empty().append(value.variable);
});
}
});
I think this shouldn't leak your memory and eventually crash your browser, even though you call it every other second or so. Give it a try and let me know how it goes.
Good luck!
Try changing it to this:
// ...
$('#details2').empty().load('links2.php').fadeIn('slow');
It may halp to explicitly tell jQuery to empty the container first, so it can free up any event handlers etc. (Though it's not clear that there would be any handlers in there ...)
edit — actually never mind; I checked the jQuery sources and it looks like calling .html() (which load() does, I'm pretty sure) seems to always call empty() first anyway.
Although an answer has been approved but I should tell you that. I had the same problem.
I found the problem in src of JQuery file. I used the JQuery site url as my source and yup it increased my computer usage to 99%. But then I downloaded the whole JQuery Script and saved it in my website directory, I used that in my source and then there was no problem with computer usage or memory. Try that too..