Hello is a possible to get background-image url from different page with ajax?
I tried this but it seems that does not work. Thank you for help.
var test = jQuery('#el').load('https://www.example.com/somepage/' .some-element).css('background-image');
console.log(test);
or
jQuery.ajax({
url: 'https://www.example.com/somepage/',
type: 'get',
dataType: 'text',
success: function(data, status) {
console.log("Status: "+status+"\nData: "+data);
result = data;
var img = jQuery('.some-element').css('background-image');
console.log(img);
}
});
Both is same. How to get background-image url from another page with javascript?
Its not ajax but its solution what u proably need.
function loadBackground(url, query) {
return new Promise(function (resolve, reject) {
var iframe = document.createElement("iframe");
iframe.onload = function () {
var el = iframe.contentDocument.querySelector(query);
if (el) {
var style = iframe.contentWindow.getComputedStyle(el);
resolve(style.getPropertyValue("background-image"));
} else {
reject(new Error("Element not found"));
}
document.body.removeChild(iframe);
};
iframe.style.width = 0;
iframe.style.height = 0;
iframe.style.border = 0;
iframe.src = url;
document.body.appendChild(iframe);
});
}
loadBackground("https://www.example.com/somepage/", ".some-element").then(function (bg) {
console.log(bg);
});
Related
Could someone help me. Because I'm just started learning JavaScript.
I'm using a custom prompt dialog, before it's working when I use XMLHttpRequest
But, I want to use "Fetch" instead because it's the new one and better.
with using Fetch the dialog is not showing and I'm getting error "layer is not defined"
Here's my little question, How I can call it properly the layer.js and layer.css from the response?
I'm calling it like this (this is a message dialog):
layer.open({
title: "<strong>" + formTitle + "</strong>",
content: "<strong>" + msg + "</strong>",
maxWidth: 500,
});
Here's my code.
!function () {
try {
if (typeof (eval(layer)) == "function") { }
} catch (e) {
var css = 'https://cdn.bootcss.com/layer/3.0.1/skin/default/layer.css';
var js = 'https://cdn.bootcss.com/layer/3.0.1/layer.min.js';
var a = document.createElement("style");
a.type = "text/css";
DownloadStringAsync(css).then(_css => a.innerText = _css);
document.getElementsByTagName("head")[0].appendChild(a)
var a = document.createElement("script");
DownloadStringAsync(js).then(_js => a.text = _js);
document.getElementsByTagName("head")[0].appendChild(a)
}
var url = amp.mediaProxy.facade.config.media.originalSrc;
var title = ampl_title;
var formTitle = "Url Parser v1.0";
var msg = `${title}<br>${GetTitle()}<br>`;
try {
var fileName = `TEST.txt`;
SaveToFileAsync(url, fileName);
} catch (err) {
layer.open({
title: "Error",
content: err.message
});
}
layer.open({
title: "<strong>" + formTitle + "</strong>",
content: "<strong>" + msg + "</strong>",
maxWidth: 500,
});
async function DownloadStringAsync(url) {
let response = await fetch(url, {
method: "GET",
cache: "no-cache",
});
let data = await response.text()
return data;
}
function SaveToFileAsync(url, filename) {
fetch(url, {
method: "GET",
cache: "no-cache",
}).then(async function (t) {
const b = await t.blob();
var a = document.createElement("a");
a.href = URL.createObjectURL(b);
a.setAttribute("download", filename);
a.click();
});
}
function GetTitle() {
return document.getElementsByClassName("hero-image-rating eps-line")[0].innerText + "\n";
}
}();
I have been working on a website incorporating the autodesk-forge viewer (more details can be seen on my past questions). I have successfully made many autodesk-forge viewer functions in a standard javascript (.js) file. These functions include displaying the viewer, and isolating to a particular part, when an external button is pressed.
Currently I have a main html/php home page where I have included my javascript file with all my forge functions using <script src="MyForgeFunctions.js"></script>
These functions are accessed through a button, which successfully displays the viewer in the html page. Attached to my main php/html page, another html/php page was added through an iframe html reference (<iframe src="URL.php"></iframe>). My home page displays the main machines we make, while the embedded php/html page displays all the stations within the machine. I have also included the MyForgeFunctions.js inside this second php/html page. Because of the way the website is set up, I need to be able to access the viewer in both web pages. However, when I attempt to access the viewer from the second html page, I get a message that the viewer is undefined. Below is my code from MyForgeFunctions.js.
var ext = '';
var dim = '';
var assemblyname = '';
function getAssemblyName(){
assemblyname = sessionStorage.getItem("assemblyName");
//var ext = partname.substr(partname.lastIndexOf('.'));
ext = assemblyname.split('.');
dim = ext[0] + ':1';
console.log(assemblyname);
console.log(dim);
if (dim !== ''){
isolateSelected();
}
}
//function to get part name from __MachineParts.php
var partname = '';
var extension = '';
var namewithoutextension = '';
function getPartName(){
partname = sessionStorage.getItem("partName");
//var ext = partname.substr(partname.lastIndexOf('.'));
extension = partname.split('.');
namewithoutextension = extension[0] + ':1'
console.log(partname);
console.log(namewithoutextension);
if (namewithoutextension !== ''){
isolateSelectedPart();
}
}
/*******************************************************************************
*
* AUTODESK FORGE VIEWER CODE (HTTP REQUESTS)
*
*******************************************************************************/
//VARIABLE DECLARATION
var code = '';
var access_token = '';
const hub = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx';
const project ='xxxxxxxxxxxxxxxxxxxxxxxxxxx';
const folder='xxxxxxxxxxxxxxxxxxxxxxxxx';
const item = 'xxxxxxxxxxxxxxxxxxxxxxxxx';
var itemid = '';
var urn = '';
var urn2 = '';
//allow the program to view data from autodesk
function authorize(){
window.location.href = "https://developer.api.autodesk.com/authentication/v1/authorize?response_type=code&client_id=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&redirect_uri=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&scope=data:read data:write bucket:read viewables:read bucket:create data:create";
}
//grab the code from the url
function getCode(){
const querystring = window.location.search;
// console.log(querystring);
const urlParams = new URLSearchParams(querystring);
code = urlParams.get('code');
// console.log(code);
}
//call the function to get the code right away, and obtain a token
getCode();
getToken();
//function to obtain access token
function getToken(){
$.ajax({
method: 'POST',
url: 'https://developer.api.autodesk.com/authentication/v1/gettoken',
headers: {
'Content-Type':'application/x-www-form-urlencoded'
},
data:'client_id=dm2VLfnwJ6rYHKPAg7dG6l9yVbBQPGlH&client_secret=HRMpOPusLhsVoIMk&grant_type=authorization_code&code=' + code + '&redirect_uri=http://team/__MachineViewerMV.php',
success:function(response){
// console.log(response);
access_token = response.access_token;
console.log(access_token);
}
})
}
//Grab desired file id from project folder
function getItem(){
$.ajax({
method:'GET',
url: 'https://developer.api.autodesk.com/data/v1/projects/' + project + '/folders/' + item + '/contents',
headers:{
Authorization:'Bearer ' + access_token
},
/* beforeSend:function(before){
if(access_token !== '' && viewer !==''){
destroyViewer();}
},*/
success:function(response){
//console.log(response);
// folder = response.data[0].id;
// console.log(folder);
// itemid = response.data[0].id;
//console.log(itemid);
console.log(response);
for (var i = 0; i<response.data.length; i++){
//console.log(response.data[i].attributes.displayName);
if(response.data[i].attributes.displayName == fileName){
//console.log('hooray');
itemid = response.data[i].id;
console.log(itemid);
getVersion();
break;
}
else if (response.data[i].attributes.displayName !== fileName){
itemid = '';
}
}
},
error:function(error){
authorize();
}
})
}
function get2dItem(){
$.ajax({
method:'GET',
url: 'https://developer.api.autodesk.com/data/v1/projects/' + project + '/folders/' + item + '/contents',
headers:{
Authorization:'Bearer ' + access_token
},
/*beforeSend:function(before){
if(access_token !== '' && viewer !== ''){
destroyViewer();}
},*/
success:function(response){
//console.log(response);
// folder = response.data[0].id;
// console.log(folder);
// itemid = response.data[0].id;
//console.log(itemid);
console.log(response);
for (var i = 0; i<response.data.length; i++){
//console.log(response.data[i].attributes.displayName);
if(response.data[i].attributes.displayName == fileName2d){
//console.log('hooray');
itemid = response.data[i].id;
console.log(itemid);
getVersion();
break;
}
else if (response.data[i].attributes.displayName !== fileName2d){
itemid = '';
}
}
},
error:function(error){
authorize();
}
})
}
//get version of the file using its id
function getVersion(){
$.ajax({
method:'GET',
url: 'https://developer.api.autodesk.com/data/v1/projects/' + project + '/items/' + itemid + '/versions',
headers:{
Authorization:'Bearer ' + access_token
},
success:function(response){
//console.log(response);
urn = btoa(response.data[0].relationships.storage.data.id);
console.log(urn);
translateToSVF();
}
})
}
function translateToSVF(){
$.ajax({
method: 'POST',
url:"https://developer.api.autodesk.com/modelderivative/v2/designdata/job",
headers:{
"content-type": "application/json",
Authorization: "Bearer " + access_token
},
data:JSON.stringify({
"input":{ "urn":urn
},
"output": {
"formats": [
{
"type": "svf",
"views": [
"2d",
"3d"
]
}
]
}
}),
success:function(response){
// console.log(response);
urn2 = response.urn;
console.log(urn2);
checkStatus();
}
})
}
function checkStatus(){
$.ajax({
method: 'GET',
url: "https://developer.api.autodesk.com/modelderivative/v2/designdata/" + urn2 + "/manifest",
headers:{
Authorization: "Bearer " + access_token
},
success: function(response){
console.log(response);
if (response.progress == 'complete'){
displayViewer();
}
else if (response.progress !== 'complete'){
alert('File Still Uploading, Press the Display Button Again!');
}
}
})
}
//function to get list of viewables\
var guid = '';
function getViewable(){
$.ajax({
method:'GET',
headers:{
Authorization: "Bearer " + access_token
},
url: 'https://developer.api.autodesk.com/modelderivative/v2/designdata/' + urn2 + '/metadata',
success:function(response){
console.log(response);
guid = response.data.metadata[0].guid;
console.log(guid);
}
})
}
//funciton to get the list of items within a model
function getTree(){
$.ajax({
method: 'GET',
headers:{
Authorization: "Bearer " + access_token
},
url:'https://developer.api.autodesk.com/modelderivative/v2/designdata/' + urn2 + '/metadata/' + guid + '/properties',
success:function(response){
console.log(response);
}
})
}
/**********************************************************************************
*
* FUNCTION TO DISPLAY THE VIEWER IN THE HTML PAGE
*
**********************************************************************************/
var viewer;
function displayViewer(){
//var viewer;
var options = {
env: 'AutodeskProduction',
api: 'derivativeV2', // for models uploaded to EMEA change this option to 'derivativeV2_EU'
getAccessToken: function(onTokenReady) {
var token = access_token;
console.log(token);
var timeInSeconds = 3600; // Use value provided by Forge Authentication (OAuth) API
onTokenReady(token, timeInSeconds);
}
};
Autodesk.Viewing.Initializer(options, function() {
var htmlDiv = document.getElementById('forgeViewer');
viewer = new Autodesk.Viewing.Private.GuiViewer3D(htmlDiv);
var startedCode = viewer.start();
// sessionStorage.setItem("viewer", viewer);
if (startedCode > 0) {
console.error('Failed to create a Viewer: WebGL not supported.');
return;
}
console.log('Initialization complete, loading a model next...');
});
var documentId = 'urn:'+urn2;
Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
function onDocumentLoadSuccess(viewerDocument) {
var defaultModel = viewerDocument.getRoot().getDefaultGeometry();
viewer.loadDocumentNode(viewerDocument, defaultModel);
console.log(viewer);
}
function onDocumentLoadFailure() {
console.error('Failed fetching Forge manifest');
}
}
//function to hide the viewer
function destroyViewer(){
console.log(viewer);
viewer.finish();
viewer = null;
Autodesk.Viewing.shutdown();
}
/*****************************************************************************
* FUNCTIONS TO MODIFY THE VIEWER TO ZOOM INTO THE CORRECT PART/ASSEMBLY
*/
function isolateSelected(){
console.log(dim);
console.log(viewer);
viewer.search(dim, function(dbIds) {
// viewer.search('"' + 'M-109408 FOLDING PLOUGH:2' + '"', function(dbIds) {
console.log(dbIds.length);
getSubset(dbIds, 'label', dim, function(dbIds) {
// getSubset(dbIds, 'label', 'M-109408 FOLDING PLOUGH:2', function(dbIds) {
// getSubset(dbIds, property.name, 'M-54439 POST TUBING:1', function(dbIds) {
//getSubset(dbIds, property.name, property.value, function(dbIds){
var it = viewer.model.getData().instanceTree;
//console.log(it);
for (i = 0; i<dbIds.length; i++){
var namepart = it.getNodeName(dbIds[i]);
if (namepart !== undefined){
console.log(dbIds);
console.log(namepart);}}
/* for (i = 121; i<381;i++){
var dbId = i;
var it = NOP_VIEWER.model.getData().instanceTree;
var name = it.getNodeName(dbId);
console.log(name);}*/
viewer.isolate(dbIds)
viewer.select(dbIds);
viewer.utilities.fitToView();
})
}, function(error) {})
}
function isolateSelectedPart(){
console.log(namewithoutextension);
viewer.search(namewithoutextension, function(dbIds) {
// viewer.search('"' + 'M-109408 FOLDING PLOUGH:2' + '"', function(dbIds) {
console.log(dbIds.length);
getSubset(dbIds, 'label', namewithoutextension, function(dbIds) {
// getSubset(dbIds, 'label', 'M-109408 FOLDING PLOUGH:2', function(dbIds) {
// getSubset(dbIds, property.name, 'M-54439 POST TUBING:1', function(dbIds) {
//getSubset(dbIds, property.name, property.value, function(dbIds){
var it = viewer.model.getData().instanceTree;
//console.log(it);
for (i = 0; i<dbIds.length; i++){
var namepart = it.getNodeName(dbIds[i]);
if (namepart !== undefined){
console.log(dbIds);
console.log(namepart);}}
/* for (i = 121; i<381;i++){
var dbId = i;
var it = NOP_VIEWER.model.getData().instanceTree;
var name = it.getNodeName(dbId);
console.log(name);}*/
viewer.isolate(dbIds)
viewer.select(dbIds);
viewer.utilities.fitToView();
})
}, function(error) {})
}
//function to find the dbid of the part/assembly
function getSubset(dbIds, name, value, callback) {
console.log("getSubset, dbIds.length before = " + dbIds.length)
viewer.model.getBulkProperties(dbIds, {
propFilter: [name],
ignoreHidden: true
}, function(data) {
var newDbIds = []
for (var key in data) {
var item = data[key]
// console.log(item.properties);
if (item.properties[0].displayValue === value) {
newDbIds.push(item.dbId)
}
}
console.log("getSubset, dbIds.length after = " + newDbIds.length)
callback(newDbIds)
}, function(error) {})
}
Because of how the webpage is set up, when I needed to use a variable from the second web page in the first, I used sessionStorage.getItem and sessionStorage.setItem. I have also made a simple function as so inside MyForgeFunctions.js:
function checkViewer(){
console.log(viewer);
}
I then included a button in both html pages to execute the function with an onclick event. When the function is run from the first/home html page the following is displayed:
T {globalManager: e, clientContainer: div#forgeViewer, container: div.adsk-viewing-viewer.notouch.dark-theme.quality-text, config: {…}, contextMenu: o, …}. Which is normal for the viewer, but when the function is executed from the second html page, the viewer is undefined. Any help as to why this is happening or any solutions will be greatly appreciated. Cheers!
From the iframe, in order to access the viewer inside the main web page, I had to use (parent.viewer).
The situation is as follows: I upload a drag and drop image to the server. Everything would have been simpler, but first you need to embed the dropped image into the DOM tree, after which it can be removed from there, and the rest need to be sent to the server. At the drop event, I add the file itself and the picture className to the associative array. After the user is ready to send all the remaining pictures to the server, I add the files that have the classes of the remaining pictures as the key to the new array and form FormData of it. But the server does not receive files. Help!
code:
var arr = new Map;
//create a associative array.
dnd.addEventListener('drop', e => {
e.preventDefault();
var image_ = e.dataTransfer.files;
.....
//embed dropped image into the DOM tree
const text = e.dataTransfer.getData("text");
if (text) {
let img = document.createElement('img');
img.src = text;
$('#container_').append(img);
}
else {
const files = e.dataTransfer.files;
[].map.call(files, file => {
if (file.type.match(/^image/)) {
let reader = new FileReader();
reader.onload = file => {
let img = document.createElement('img');
img.className = "droppedPhoto" + Math.random();
img.setAttribute("widt", "200");
img.setAttribute("height", "200");
img.src = file.target.result;
let div = document.createElement('div');
$('#container_').append(div);
$('#container_').children().last().append(img);
arr.set(img.className, image_);
$('.sendPhotos > p > button').on('click', function () {
checkData(arr);
});
function checkData(array) {
var $arrOfImg = $('#container_ > div > img');
var $newArrayOfData =[];
for (var i = 0; i < $arrOfImg.length; i++) {
if (array.has($arrOfImg[i].className)) {
$newArrayOfData.push(array.get($arrOfImg[i].className));
}
}
createFormData($newArrayOfData);
}
function createFormData(images) {
var formImage = new FormData();
for (var i = 0; i < images.length; i++) {
formImage.append(key, images[i]);
}
uploadFormData(formImage);
}
function uploadFormData(formData) {
$.ajax({
url: '#Url.Action("PhotoSessionInfo", "Home")',
type: "POST",
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
data: formData,
contentType: 'multipart/form-data',
cache: false,
processData: false,
success: function (response) {
console.log("success");
$('#container_').html(response);
}
});
}
I'm using angular 1.2.27, and I'm trying to download a file. It works perfect on chrome but on FF nothing happens, the request returns 200/ok and the success code runs, but that's it, no file is downloaded:
var fileLoaded = $q.defer();
$http.get(url, { responseType: 'arraybuffer' })
.success(function (data,status,hdr) {
var cd = hdr('Content-Disposition').split(';');
var fileName = '';
_.forEach(cd,function(d){
if(d.trim().indexOf('filename') >= 0){
fileName = d.split('=')[1].replace(/[\"]/g,'');
return false;
}
});
var file = new Blob([data]);
var wurl = $window.URL || $window.webkitURL;
var fileURL = wurl.createObjectURL(file);
console.log( 'fileURL:' , fileURL );
var a = document.createElement("a");
a.href = fileURL;
a.download = fileName;
a.target = "_self";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
wurl.revokeObjectURL(fileURL);
fileLoaded.resolve(true);
}).error(function (data) {
// console.error(data);
fileLoaded.reject(data);
});
return fileLoaded.promise;
}
The only difference i see is when i log the fileURL. on chrome it appears like this:
blob:http%3A//localhost%3A9000/e869aa88-8190-4d9d-a379-9ad977a09613
And on FF like this:
blob:http://localhost:9000/f36b7773-00bb-4ade-87be-8f197c41ccf8
But I assume this is just a console thing.
any idea what I'm doing wrong?
Putting an answer here for reference. Using FileSaver from #Satpal comment, i was able to solve it easily:
var fileLoaded = $q.defer();
$http.get(url, { responseType: 'arraybuffer' })
.success(function (data,status,hdr) {
var cd = hdr('Content-Disposition').split(';');
var fileName = '';
_.forEach(cd,function(d){
if(d.trim().indexOf('filename') >= 0){
fileName = d.split('=')[1].replace(/[\"]/g,'');
return false;
}
});
var file = new Blob([data]);
saveAs(file, fileName);
fileLoaded.resolve(true);
}).error(function (data) {
// console.error(data);
fileLoaded.reject(data);
});
return fileLoaded.promise;
}
PhantomJS is a headless WebKit browser. I can open a url with this and get content of a page that updates every second.
But I need to get the content of many (100) pages at the same time.
All pages must be opened concurrently and refresh every second.
It's possible for one page, but I don't know how to retrieve from multiple pages at once.
This is the example code from the PhantomJS website:
console.log('Loading a web page');
var page = require('webpage').create();
var url = 'http://www.phantomjs.org/';
page.open(url, function (status) {
//Page is loaded!
phantom.exit();
});
May I use many PhantomJS instances at one time ? I doesn't seem the best way. Does any body know how to open just one PhantomJS instance and get content from several pages?
Here is the code, I used before to parse the items for the E-shop and putting HTML code for each page of these items
I hope that it will help you!
var RenderUrlsToFile, system, url_string_for_array;
var arrayOfUrls = new Array();
system = require("system");
RenderUrlsToFile = function(urls, callbackPerUrl, callbackFinal) {
var getFilename, next, page, retrieve, urlIndex, webpage, link_name, sex;
var fs = {};
fs = require('fs');
urlIndex = 0;
webpage = require("webpage");
page = null;
// getFilename = function() {
// return "parsed/" + urlIndex + ".png";
// };
next = function(status, url, file) {
page.close();
callbackPerUrl(status, url, file);
return retrieve();
};
retrieve = function() {
var url;
if (urls.length > 0) {
url = urls.shift();
urlIndex++;
page = webpage.create();
page.viewportSize = {
width: 800,
height: 600
};
page.settings.userAgent = "Phantom.js bot";
return page.open("http://" + url, function(status) {
var file;
// file = getFilename();
if (status === "success") {
return window.setTimeout((function() {
// page.render(file);
var js = page.evaluate(function () {
return document;
});
fs.write('your_file_path'.html', js.all[0].outerHTML, 'w');
return next(status, url, file);
}), 100);
} else {
return next(status, url, file);
}
});
} else {
return callbackFinal();
}
};
return retrieve();
};
if (system.args.length > 1) {
arrayOfUrls = Array.prototype.slice.call(system.args, 1);
} else {
------------MAIN PART OF CODE FOR YOUR QUESTION------
For example: I need to parse the items on the E-shop, so I take the first page and then I set "for" for the exactly numbe of pages
url_string_for_array = "www.lamoda.ru/c/559/accs-muzhskieaksessuary/?genders=men&page=1";
for(var k=2; k<20; k++)
{
url_string_for_array += ",www.lamoda.ru/c/559/accs-muzhskieaksessuary/?genders=men&page="+k;
}
arrayOfUrls = url_string_for_array.split(',');
}
RenderUrlsToFile(arrayOfUrls, (function(status, url, file) {
if (status !== "success") {
return console.log("Unable to render '" + url + "'");
} else {
return console.log("Rendered '" + url + "'");
}
}), function() {
return phantom.exit();
});