Currently I'm using Javascript with Ajax to fetch some data and present it in a new window. I'm trying to close the window in OpenFileWindow() before a new one is opened, but while the it finds the window object, all properties and methods give a permission denied error.
I'm believe it has to do with scoping with the Ajax call as when I open the window before XMLHttpRequest, there's no problem.
I'm not sure how to proceed and I've searched quite a bit. Anyone have any suggestions? Thanks.
opened
var newWin = null;
function View_onClick(propId, url) {
var param = "propId=" + propId;
param += "&filename=" + url;
var xhr = new XMLHttpRequest();
xhr.open("POST", "GetActivityFileName.ashx", false);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
if (xhr.responseText == "") {
alert("Sorry unable to find file.");
return false;
}
else {
OpenFileWindow(xhr.responseText)
return false;
}
}
}
}
xhr.send(param);
return false;
}
function OpenFileWindow(fileUrl) {
if(newWin != null)
newWin.close();
newWin = window.open(fileUrl);
newWin.focus();
}
If your intention is to just re-use the window, why not name it.
If you give the same name as the 2nd parameter of window.open, it will re-use that window.
How about this. If the window is still open, change the URL. Otherwise, open the window and load the URL.
function OpenFileWindow(fileUrl) {
if(newWin == null || newWin.closed)
newWin = window.open(fileUrl);
else
newWin.location.replace(fileUrl);
newWin.focus();
}
Related
I'm developing a plugin for Chrome and it has History feature in the plugin. For example, clicking the button creates a new tab and saves the URL address in the history. So this function works fine. But I want to get the document.title data of the tab that was opened in the past instead of the URL address. I tried doing this with tabs[tabs.length-1].title but it didn't get the title of the opened tab. Instead it got the title of the last tab that was already open. I guess this is the problem because the tab is not open yet. How can I solve this? Can you help me please?
This is my create tab function (If the tab is already open, don't open it again.):
function openTab(tab_url) {
var isTabActive = false;
var tabId = 0;
var tabTitle = "";
totalHistoryContent++;
chrome.tabs.query({}, function(tabs) {
for(var i=0;i<tabs.length;i++) {
if(tabs[i].url.toLowerCase().includes(tab_url.toLowerCase()) == true) {
isTabActive = true;
tabId = tabs[i].id;
tabTitle = tabs[i].title; // WORKING NICE
break;
}
}
if(isTabActive == false) {
chrome.tabs.create({ url:tab_url });
tabTitle = tabs[tabs.length - 1].title; // NOT WORKING CORRECTLY
} else{
chrome.tabs.update(tabId, {selected: true});
chrome.tabs.reload(tabId);
}
alert(tabTitle);
});
if(tab_url !== "chrome-extension://" + chrome.runtime.id + "/popup.html" && tab_url !== "chrome://extensions/?id=" + chrome.runtime.id) {
setHistory(tabTitle,49); //THIS FUNCTION SAVE TITLE TO HISTORY
}
}
One of the ways that you can handle this problem is sending an ajax request to the page's url
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', 'tab_url', true);
xmlHttp.onreadystatechange = function () {
if (
this.readyState == 4 &&
((this.status >= 200 && this.status < 300) ||
this.status == 304)
) {
var data = this.responseText;
var contentType = this.getResponseHeader("Content-Type"); //no i18n
if (contentType && contentType.match('text/html')) {
var doc = new DOMParser().parseFromString(data, "text/html");
console.log(doc.title);
}
}
};
xmlHttp.send();
Note: This may throw CORS error at most pages, so don't forget to add "<all_urls>" in permissions in manifest(assuming you are using manifest V2).
"permissions": [
"<all_urls>"
],
If you are using manifest V3, which is recommended, refer this documentation regarding permission
Other way is to send a message from chrome.tabs.create success callback to content script, if you don't use content script you have to inject code. In message response you can send the document's title using document.title.
Either way both will be asynchronous...
I have a servlet that generates a PDF and the output goes to a new browser window.
I am attempting to replace the title of that new window using the updateTitle() function below.
However, when I try to assign the report name (repName) to the window instance, IE11 throws a "Permission denied" error. Any ideas?
function showReport(url, repName){
var repWin = window.open(url);
updateTitle(repWin, repName)
}
function updateTitle(repWin, repName) {
setTimeout(function() {
repWin.document.title = repName; //IE11 console throws PERMISSION DENIED here
}, 3000);
}
You will need to use something like postMessage.
On your original window:
function showReport(url, repName) {
var repWin = window.open(url);
repWin.postMessage('setTitle:' + repName, '*');
}
On the repWin:
function updateTitle(message) {
var m = message.data.split(':'),
eventType = m[0],
data = m[1];
if (message.origin === 'YOUR_URL_HERE' && eventType === 'setTitle' ) {
repWin.document.title = data;
}
}
window.addEventListener("message", updateTitle, false);
Note: This will obviously only work if you can modify the source for the window you are opening.
I`am working on a js file which was designed for a home page.
I would like to navigate from this page to other pages via a navigation menu bar.
The target pages are sharing the same templat(a html code), thus for going to a specific page I need to load a specific content, which is saved in a xml file, then pass its contents to the target page.
function loadFileToElement(filename, elementId)
{
var xhr = new XMLHttpRequest();
try
{
xhr.open("GET", filename, false);
xhr.send(null);
}
catch (e) {
window.alert("Unable to load the requested file.");
}
// Until this point I can load the specific content
// How can I get from the url of the target page
// a js document object, so that I can call getElementById(Id)
// to pass the specific content.
// For instance: Im currently opnening X1:= www.main.com
// und I would like to switch to X2 := www.targetpage.com
// target page which contains html the templat.
// The problem **document** represents currently X1
// but i would like to set it to X2 so that I can pass
// the content of xhr.responseText to it
var component = **document**.getElementById(elementId);
component.innerHTML = xhr.responseText;
}
Thanks
Try this, I have added xhr.onload function, which populated text returned from response
function loadFileToElement(filename, elementId)
{
var xhr = new XMLHttpRequest();
try
{
xhr.open("GET", filename, false);
xhr.onload = function () {
var component = document.getElementById(elementId);
component.innerHTML = xhr.responseText;
}
xhr.send(null);
}
catch (e) {
window.alert("Unable to load the requested file.");
}
}
You can also use onreadystatechange event instead of onload. click for more reference
Try this
function loadFileToElement(filename, elementId)
{
var xhr = new XMLHttpRequest();
try
{
xhr.open("GET", filename, false);
xhr.onload = function () {
var com = document.getElementById(elementId);
com.innerHTML = xhr.responseText;
}
xhr.send();
}
catch (e) {
window.alert("Unable to load the requested file.");
}
}
Reference
I'm trying to have a div refresh after a callback using ajax functions. Basically, I want /includes/view_game/achievements.inc.php to be reloaded in the div #achievements_tab. The callback (I didn't include it in codes below) works well and triggers the AchievementRefresh function found below (the opacity of the div changes to 0.5, but it remains like this and the refresh is not made).
Those two functions are used for another similar ajax refresh on my site that works well. So I tried to modify the code, but since it's for a slightly different purpose, maybe I have the wrong approach.
function AjaxPost(url, success_function) {
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("Your browser doesn't support AJAX. You should upgrade it!")
return
}
xmlHttp.onreadystatechange = success_function;
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
This AjaxPost function is used in the other function below:
function AchievementRefresh() {
div('achievements_tab').style.opacity = 0.5;
div('highscore_pages').innerHTML = '<img src="'+site_url+'/images/loader.gif" />';
AjaxPost(site_url+"/includes/view_game/achievements.inc.php?", '',
function () {
div('achievements_tab').innerHTML = xmlHttp.responseText;
div('achievements_tab').style.opacity = 1;
}
)
}
Use load
$('#achievements_tab').load('/includes/view_game/achievements.inc.php');
See: http://api.jquery.com/load/
Edit
E.g.
function AchievementRefresh() {
$('#achievements_tab').css('opacity', 0.5);
$('#highscore_pages').html('<img src="'+site_url+'/images/loader.gif" />');
$('#achievements_tab').load('/includes/view_game/achievements.inc.php')
.success(function() {
$('#achievements_tab').css('opacity', 1);
});
}
Try this.
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
div('achievements_tab').innerHTML = xmlHttp.responseText;
div('achievements_tab').style.opacity = 1;
}
}
};`
Name and id is example.
Also, some changes:
AjaxPost(site_url+"/includes/view_game/achievements.inc.php");
var params= 'name'+encodeURIComponent(name)+'&id='+encodeURIComponent(id)
Parameters shouldn't be in URL.
xmlhttp.send(params);
Is there a way (preferrably using JavaScript) to determine whether a URL is to a SWF or a JPG?
The obvious answer is to sniff the filename for ".jpg" or ".swf" but I'm dealing with banners that are dynamically decided by the server and usually have a lot of parameters and generally don't include an extension.
so i'm wondering if I could load the file first and then read it somehow to determine whether it's SWF or JPG, and then place it, because the JavaScript code I'd need to display a JPG vs a SWF is very different.
Thanks!
You could use javascript to detect if it is a image by creating a dynamic img-tag.
function isImage(url, callback) {
var img = document.createElement('img');
img.onload = function() {
callback(url);
}
img.src = url;
}
And then calling it with:
isImage('http://animals.nationalgeographic.com/staticfiles/NGS/Shared/StaticFiles/animals/images/primary/bald-eagle-head.jpg', function(url) { alert(url + ' is a image'); });
Update
This version will always execute the callback with a boolean value.
function isImage(url) {
var img = document.createElement('img');
img.onload = function() {
isImageCallback(url, true);
}
img.onerror = function() {
isImageCallback(url, false);
}
img.src = url;
}
function isImageCallback(url, result) {
if (result)
alert(url + ' is an image');
else
alert(url + ' is not an image');
}
Put your logic in the isImageCallback function.
I would extend Sijin's answer by saying:
An HTTP HEAD request to the url can be used to examine the resource's mime-type. You
won't need to download the rest of the file that way.
Completely untested, basicly just an idea:
function isImage(url)
{
var http = getHTTPObject();
http.onreadystatechange = function ()
{
if (http.readyState == 4)
{
var contentType = http.getResponseHeader("Content Type");
if (contentType == "image/gif" || contentType == "image/jpeg")
return true;
else
return false;
}
}
http.open("HEAD",url,true);
http.send(null);
}
function getHTTPObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
else
{
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
return false;
}
I am not sure the of the exact setup you have, but can you use the HTTP response and check the mime-type to determine image vs flash?
If the URL doesn't have an extension then there is no way to tell without requesting the file from the server.