I am trying to load the same link of the tab into the popup window (this is not my primary purpose and i am doing this just to get acquainted) I am getting the error
Failed to load resource: net::ERR_FILE_NOT_FOUND
My js file is as follows
var pageGenerator = {
requestPage: function() {
var urlTosearch;
chrome.windows.getCurrent(function(w) {
chrome.tabs.getSelected(w.id,
function (response){
urlTosearch = response.url;
});
});
var req = new XMLHttpRequest();
req.open("GET", urlTosearch, true);
req.onload = this.loadPage_.bind(this);
req.send(null);
},
loadPage_: function (e) {
var resp = e.target.responseText;
document.body.insertAdjacentHTML( 'beforeend', resp);
}
};
document.addEventListener('DOMContentLoaded', function () {
pageGenerator.requestPage();
});
I have read that external pages can not be loaded onto the popup. Is it so? If true why? and if not how can it be done?
When receiving Failed to load resource: net::ERR_FILE_NOT_FOUND you probably didn't defined your url correctly. Since i don't see your url in your piece of code and i see no accepted answer i will share what i think goes wrong.
At first you have to define the url you are posting in your manifest with:
"permissions": [
"http://www.yoururl.com/"
],
Also when calling your api by: yoururl.com/ the chrome extension will not call the api. Just simply because it thinks the url is withing the scope of your extension locally. To solve this you have to define http://www. or https://www. Now Chrome will recognize you try to load something from outside of the extension.
Try using the Active Tab permission FROM A BACKGROUND script in order the get the URL of the current page. Then use chrome.tabs.create() to open a new tab with that same URL.
Details here: https://developer.chrome.com/extensions/activeTab
Related
In Chrome I have populate an on line mapping tool (Kumu) with a JSON file from the JS Console with:
Workflows.setCurrentMapSource("MY_JSON_LINK");
where MY_JSON_LINK was:
https://XXXXXX/json?key=MTE3.DI4LYA.ZrzRFJ5o7Q5m3nLe6d6JGFISdKI
But the Link is no longer active so when I go to the Kumu page I get the error:
Unable to open map
Is there a way to break the connection from the JS Console? I have searched but have not found anything that works
Thanks
I'm on phone so I can't give you the code, but what you can do is override the XMLHttpRequest methods and then you can manipulate any requests done on the page.
But this must of course be done BEFORE the requests are done so you'll probably need Tampermonkey userscript. Example:
const originalOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function (){
//do what you need
originalOpen. apply(this, arguments);
}
So for example if you want to protect some link from being accessed, you can do this:
const originalOpen = XMLHttpRequest.prototype.open;
const REGEX_TEST_URL = /https?:\/\/XXXXXX\/json?key=(.*?)/
XMLHttpRequest.prototype.open = function (method, url){
console.log("Open: ", url);
/// if you want to kill access to that URL
if(REGEX_TEST_URL.test(url))
throw new Error("Blocked loading of URL "+url)
//Otherwise allow normal operatio to proceed
originalOpen.apply(this, arguments);
}
You can test this even here on stackoverflow.
I have a .php file running that is generating a downloadable file; when the .php file runs it opens a tab in the browser. Occasionally the .php file takes up to 15 seconds depending on the conditions to create the file.
I would like to know when this tab is open generating the downloadable file and when it closes. This way I can have some sort of loading message displayed while the file is being generated. When the .php file is done creating the file it automatically closes the tab.
Code:
var win = window.open(download, '_blank'); //opens the php file which generates the file.
if (win)
{
win.focus();
//have some sort of message stating to wait for the file to download here and then close it when the php file finishes running.
}
else
{
alert("Please allow popups.");
}
closePopup2();
I would suggest not opening a PHP file in a new tab, but using XMLHttpRequest(), you can find a guide on how to use it on MDN
You can use it like this:
function reqListener () {
console.log(this.responseText); // Will log full output of page
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", download);
oReq.send();
Give your window a unique id so the script will know which one to check (maybe needs to be random if opened/closed multiple times). I don't know if you need to focus, and popup permission is for you to figure out, but I think following should work:
var win = window.open(download, 'windowID', 'width:300px;height:300px');
win.document.write("<p>One moment please!</p>");
win.focus();
var test = setInterval(function() {
if(win.closed) {
clearInterval(test);
// do you stuff here after window closed
}
}, 500);
I'm currently working through the book "Head first HTML5 programming". I want to load the content of a file named sales.json from a web server on my own machine. I used wampserver for this.
In the folder wamp/www/gumball/ I put all relevant .html, .js and .css files, and also the sales.json file.
My JavaScript code is very simple:
window.onload = function() {
var url = "http://localhost/gumball/sales.json";
var request = new XMLHttpRequest();
request.open("GET", url);
request.onload = function() {
if (request.status == 200) {
updateSales(request.responseText);
}
};
request.send(null);
}
function updateSales(responseText) {
var salesDiv = document.getElementById("sales");
salesDiv.innerHTML = responseText;
}
This doesn't do anything! Typing the link: http://localhost/gumball/sales.json in my browser opens the right file, so the link should be correct. Even when using the .js files that come with the book (with a finished version of the application I'm trying to make), nothing loads.
Testing with alert statements tells me the request.onload event never happens. I'm clueless as to why this is the case.
A fact I don't quite understand yet: when I type: http://localhost/gumball/sales.json: in my browser (I added a colon at the end of the link), I get a 403 Forbidden error! Why does this happen? Does this have something to do with my problem?
I open html document with firefox
Your HTML document must be open with a URL in http://, not file://, if you want it to be able to open in javascript another document, unless the second document is served with relevant CORS headers.
This is due to same origin policy.
As you have a local WAMP server, there is no problem : simply open your file using a http:// URL like you do for your JSON file.
From my knowledge it is not possible directly by getting tab.url (only possible in the popup.html) and doing message passing also requires that popup.html be open. Is there anyway to bypass this and get the current page url from background.html?
My best shot was with message passing, which I used this code in background.html
var bg = chrome.extension.getPopupPage();
var myURL = bg.myURL;
then in popup.html I had:
chrome.tabs.getSelected(null, function(tab) {
var myURL = tab.url;
})
Anyways the above does't work at all. Anybody know of a way to do this without having to actually open up the popup?
chrome.tabs.query is supported from background pages, of course as long as you have the tabs permission. This is the supported route as of Chrome 19.
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
var tab = tabs[0];
var url = tab.url;
});
Note that currentWindow is needed because it would otherwise return the active tab for every window. This should be guaranteed to only return one tab.
Of course, keep in mind that this is an asynchronous API – you can’t access any data it provides except from within the callback function. You can store values (such as url here) at a higher scope so another function can access it, but that will still only provide the correct result after the callback is executed.
(The below is my original answer kept for posterity – this method is no longer necessary, requires an always-running background page, and getSelected() is deprecated.)
First put this in background.html and make the myURL variable global:
var myURL = "about:blank"; // A default url just in case below code doesn't work
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) { // onUpdated should fire when the selected tab is changed or a link is clicked
chrome.tabs.getSelected(null, function(tab) {
myURL = tab.url;
});
});
Then run this in popup.html when you want to get the page url:
chrome.extension.getBackgroundPage().myURL;
So if I were to make that appear inside the popup and I went to Google and clicked your page or browser action, I'll see http://google.com/webhp in the popup.
Upon seeing this post I felt that there should be a way to mark a discussion as "obsolete".
Reasons being...
This question needs to migrate to manifest v2 and...
The answers both are not working. I am using a select onchange and posting the current tab's url which is not working.
Might be these all worked in manifest v1.
My answer is ...
var myURL = "not set yet";
window.addEventListener('load', function () {
chrome.tabs.getSelected(null,function(tab){
myURL=tab.url;
});
This is a little more work but works like a charm...
I would use a content script; it's relatively simple & allows you to get any info from current page you might want. Have the background page "inject" the script into the current webpage to gather the info you need. The script then just passes it back to the background.
background.js:
// Icon is clicked and triggers content script to be injected into current webpage
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, { file: 'inject.js' });
});
// Listens for message back from content script and then runs
chrome.runtime.onMessage.addListener(function (request) {
var URL = request.url;
});
inject.js (content script):
// Gathers up in the information that you need from webpage
var pageInfo = {
"url": window.location.href
};
// Sends the information back to background.js
chrome.runtime.sendMessage(pageInfo);
Hope this helps someone!
chrome.tabs.getSelected(null, function(tab) {
var myURL = tab.url;
});
I don not understand, the code above can be used in background page to get the current tab's url.
I have a widget that contains an iframe. The user can configure the url of this iframe, but if the url could not be loaded (it does not exists or the user does not have access to internet) then the iframe should failover to a default offline page.
The question is, how can I detect if the iframe could be loaded or not? I tried subscribing to the 'load' event, and, if this event is not fired after some time then I failover, but this only works in Firefox, since IE and Chrome fires the 'load' event when the "Page Not Found" is displayed.
I found the following link via Google: http://wordpressapi.com/2010/01/28/check-iframes-loaded-completely-browser/
Don't know if it solves the 'Page Not Found' issue.
<script type="javascript">
var iframe = document.createElement("iframe");
iframe.src = "http://www.your_iframe.com/";
if (navigator.userAgent.indexOf("MSIE") > -1 && !window.opera) {
iframe.onreadystatechange = function(){
if (iframe.readyState == "complete"){
alert("Iframe is now loaded.");
}
};
} else {
iframe.onload = function(){
alert("Iframe is now loaded.");
};
}
</script>
I haven't tried it myself, so I don't know if it works. Good luck!
Nowadays the browsers have a series of security limitations that keep you away from the content of an iframe (if it isn´t of your domain).
If you really need that functionality, you have to build a server page that have to work as a proxy, that receive the url as a parameter, test if it is a valid url, and does the redirect or display the error page.
If you control the content of the iframe, the iframe can send a message to the parent.
parent.postMessage('iframeIsDone', '*');
The parent callback listens for the message.
var attachFuncEvent = "message";
var attachFunc = window.addEventListener ;
if (! window.addEventListener) {
attachFunc = window.attachEvent;
attachFuncEvent = "onmessage";
}
attachFunc(attachFuncEvent, function(event) {
if (event.data == 'iframeIsDone') { // iframe is done callback here
}
});
How about checking if the url is available and only then setting the actual url of the iframe?
e.g. with JQuery
var url = "google.com"
var loading_url = "/empty.html"
document.getElementById("iframe").src = loading_url;
$.ajax({
url: url,
type: 'GET',
complete: function(e, xhr, settings){
if(e.status === 200){
document.getElementById("iframe").src = url;
}
}
});
Edit:
This does not seem to work cross domain, the status code is 0 in those cases.
If you have control over the contents of the iframe (e.g. you can add arbitrary code to the page), you can try to implement a special function in each of them, then in your page, you call that function and catch an error (via window.onerror handler) if the function called via eval fails because the page didn't load.
Here's example code: http://www.tek-tips.com/viewthread.cfm?qid=1114265&page=420
After the onload fires, you can scavenge the content of the iframe to see if it contains a usefull page or not. You'd have to make this browser specifuc unfortunately because they all display a different "page not found" message.
For more info, take a look here at http://roneiv.wordpress.com/2008/01/18/get-the-content-of-an-iframe-in-javascript-crossbrowser-solution-for-both-ie-and-firefox/