Using html code from dataset in dynamic pages

Hello All,
I’m working on a project where I will be using iframe to embed code in my dynamic pages. The dataset name is dynamicDataset and the dataset has many columns like title, description, etc. and the iframe code is embed in the id called html2 and field type is text. The iframe name is html16.

The html code in the iframe “html16” is

<!doctype html>
<html>
<head>
<script type="text/javascript">
window.onmessage = (event) => {
if (event.data) {
document.getElementById("dynamicElement").innerHTML = event.data;
}
};
function load () {
window.parent.postMessage("page loaded");
}
</script>
</head>
<body onload="load ();" style="background-color:#ffffff;">
<div id="dynamicElement"></div>
</body>  

The page code is

let urlMessage = $w('#dynamicDataset').getCurrentItem().html2;
$w("#html16").onMessage( (event) => {   				   
$w("#html16").postMessage(urlMessage);
});

I tweaked the above code from this discussion I found on wix: link

The code worked when I tried with url but for html code its not working
Need help!

First get your values out of your DB via a connected —> DATASET or by using a Wix-Data-Query and put them to a VARIABLE…

Something like …

let datafield = "xxxx"
let value = "yyy"

wixData.query("YourDatabaseNameHere")
.eq(datafield, value)
.find()
.then((res)=>{console.log(res)
	let myData = res.items
	//...and so on
});

At the end of the query you have your DATA —> “myData”, which will include all your DATABASE-VALUES.

Now you want to push this data ( “myData”) to your HTML…

           
 $w("#html1").postMessage("myData");

…and recieve this data in your HTML-Component…

HTML-CODE…

<!doctype html>
<html>
<head>
    <script type="text/javascript">
        function load_Message() {
            window.onmessage = (event) => {
                if(event.data) {
                    document.getElementById("xxxxx").innerHTML = event.data;
                }
            }
        }
 
    </script>
</head>
<body onload="load_Message();" style="background-color:#ff00ff;">
    <div id="xxxxx"></div>
</body>  

As example, take a look onto this post here…

You will find this working CODE on this site…

$w.onReady(()=>{
    $w("#dataset1").onReady(async()=>{
       let urlMessage = $w('#dataset1').getCurrentItem(); 
       console.log(urlMessage);          
       $w("#html1").postMessage(urlMessage);
 
       let length = await $w('#dataset1').getTotalCount(); 
       console.log("Data-Length: ", length);
 
        $w('#button1').onClick(async()=>{console.log("Click")
           let code = await ($w('#yourcode').value).toString(); 
           console.log("Input-Code: ", code)
           let data = await ($w("#dataset1").getItems(0,length)); 
           console.log("Data: ", data)

           for(var i=0; i<length ;i++){
               let dataCode = String(data.items[i].cxCode); 
               console.log("CODE: ", dataCode)
 
               if(dataCode===code){console.log("CODE found!")
                  $w('#button2').enable();
               }
               else{console.log("ERROR: No matching CODE found!")
                  $w('#button2').disable();
               }
            }
        });
    });
});


/*
<!doctype html>
<html>
<head>
    <script type="text/javascript">
        function load_Message() {
            window.onmessage = (event) => {
                if(event.data) {
                    document.getElementById("xxxxx").innerHTML = event.data.cxCode;
                }
            }
        }
 
    </script>
</head>
<body onload="load_Message();" style="background-color:#ff0fff;">
<div id="xxxxx"></div>
</body>   
*/

This example shows you how to do it, by using —> DATASETS instead of —> WixData-Queries.

1 Like

Thank you for your answer. I just have few doubt

  1. Should I put my fieldname from data here. let datafield= “html2” in my case as the iframe code is in this field key.

  2. What should I enter in let value=“yyyy” can it be any random variable or something related to my dataset.

  3. What should I enter in the html code document.getElementbyId(“xxxxxx”).innerhtml
    I don’t have a great understanding about codes. Could you please simply this for me.
    Thank you once again

Show me your DATABASE or an example of your DATABASE.

Hi @russian-dima
I have attached the images of my dataset


Would this help?

This is how you will get your DATA out of your DB…

import wixData from 'wix-data';

$w.onReady(()=>{
    wixData.query("Properties")
    .find()
    .then( (results) => {
 if(results.items.length > 0) {
 let firstItem = results.items[0]; console.log("First-Item: ", firstItem)
 let items = results.items; console.log("Items: ", items)


        } 
 else {  }
    })
    .catch( (err) => {let errorMsg = err; console.log(errorMsg)});
});

Now you have your DATA-PACKAGE in a VARIABLE called —> “items”.
The CONSOLE shows you the ITEM-PACKAGE (all items) and also the first item of the found ITEMS-PACKAGE.

Add some new code-lines like…
console.log(items[0].html2)
console.log(items[1].html2)
console.log(items[2].html2)
console.log(items[3].html2)

And take a look into CONSOLE to see the results.

Now you have the choice what exactly you want to send to your HTML-Component?

I assume you want to send the whole ITEM-PACKAGE —> “items”.

$w("#html1").postMessage(items);

And recieve your items in your HTML-Component…

function load_Message() {
    window.onmessage = (event) => {
        if(event.data) {
            console.log("Recieved-HTML-Data: ", data)
            console.log("Recieved-HTML-Data1: ", data[0])
            console.log("Recieved-HTML-Data1-html2: ", data[0].html2)
        }
    }
}

And so on…

1 Like

Thank you very much @russian-dima
I’ll try this but still I’m but confused where to add the console.log(item[0].html2)
Should I add it with the 1st code you mentioned?
And what does the data[1], data [0]?
I have to display 1 code per page e.g. page 1 will have code 1, page 2 will have code 2 and so on.
sorry for this questions. I’m a newbie and recently I have started training on html and have no background on coding.
Sorry for the trouble :sweat_smile::sweat_smile:

Hi @russian-dima I tweaked and tried the codes which you shared

 import wixData from 'wix-data';

$w.onReady(()=>{
    wixData.query("Properties")
 .find()
 .then( (results) => {
 if(results.items.length > 0) {
 let firstItem = results.items[9]; console.log("adobepdf: ", firstItem)
 let items = results.items; console.log("code: ", items)
console.log(items[10].adobepdf)
 } 
 
 })
 .catch( (err) => {let errorMsg = err; console.log(errorMsg)});
});

Here adobepdf is my fieldname (same fieldkey a text field) and I want to display codes for 5 dynamic pages (1 code per page) from items 9 to 14 which can be seen in the console in preview mode.

Console screenshot
The code marked is what I want to display in the iframe

in the iframe the code I didn’t understood what to change

function load_Message() {
    window.onmessage = (event) => {
        if(event.data) {
            console.log("Recieved-HTML-Data: ", data)
            console.log("Recieved-HTML-Data9: ", item[9])
            console.log("Recieved-HTML-Data9-adobepdf: ", item[9].adobepdf)
        }
    }
}

The postmessage code is

$w("#html6").postMessage('code');


Please help!

I’ll try this but still I’m but confused where to add the console.log(item[0].html2)
Should I add it with the 1st code you mentioned?

import wixData from'wix-data';  
$w.onReady(()=>{     
    wixData.query("Properties").find().then((results)=>{
        if(results.items.length >0){
           let firstItem = results.items[0]; console.log("First-Item: ", firstItem)
           let items = results.items; console.log("Items: ", items)
           
           console.log(items[0].html2)
           console.log(items[1].html2)
           console.log(items[2].html2)
           console.log(items[3].html2)
           $w("#html1").postMessage(items); //<---- send DATA to ---> HTML-component
        }
        else{}
    }).catch((err)=>{let errorMsg = err; console.log(errorMsg)});
});

HTML-CODE:

<!doctype html>
<html>
<head>
    <script type="text/javascript">
        function load_Message() {
            window.onmessage = (event) => {
                if(event.data) {
                    console.log(data[0].html2)
                    console.log(data[1].html2)
                    console.log(data[2].html2)
                    console.log(data[3].html2)
                    document.getElementById("xxxxx").innerHTML = event.data.cxCode;
                }
            }
        }
 
    </script>
</head>
<body onload="load_Message();" style="background-color:#ff0fff;">
<div id="xxxxx">
    <p id="sss"></>
</div>
</body>  
1 Like

Thank you @russian-dima
I tried the code but the html shows a purple screen. Now I’m stuck here please help

The Html code is


<!doctype html>
<html>
<head>
    <script type="text/javascript">
        function load_Message() {
            window.onmessage = (event) => {
                if(event.data) {
                    console.log(data[9].adobepdf)
                    document.getElementById("dynamicElement").innerHTML = event.data.cxCode;
                }
            }
        }
 
    </script>
</head>
<body onload="load_Message();" style="background-color:#ff0fff;">
<div id="dynamicElement">
    <p id="sss"></>
</div>
</body>  

what should I enter in the highlighted part

Just one more doubt the field whose data I want to populate in the iframe has both fieldname and fieldkey as adobepdf and it is text type field

Please help

When you get a purple screen, that means that it works like it should.
To change the color of your HTML-Component…you can do it here…

<body onload="load_Message();" style="background-color:#ff0fff;">

Change → from —>

#ff0fff

…to…

#ffffff

You should also be able to use predefined colors like…

"white"
"black"
"green"
"blue"
"orange"

and so on.

The highlited part are the
Please read about how to work with DIVs and HTML5.

Also use → google to find more information about DIVs and HTML5.

You have now all informations to be able to work and complete your project.
All you have to do right now is first to understand completely the whole code and how it is working.

For testing create more DIV-elements…

functionload_Message(){             
   window.onmessage=(event)=>{
      if(event.data){                     
         console.log(data[9].adobepdf)                            
         document.getElementById("DIV1").innerHTML = event.data[6].adobepdf;
         document.getElementById("DIV2").innerHTML = event.data[7].adobepdf;
         document.getElementById("DIV3").innerHTML = event.data[8].adobepdf;
         document.getElementById("DIV4").innerHTML = event.data[9].adobepdf;
      }
   }
}
<body onload="load_Message();" style="background-color:#ffffff;">
<div id="DIV1"></></div>
<div id="DIV2"></></div>
<div id="DIV3"></></div>
<div id="DIV4"></></div>
<div id="DIV5"></></div>
</body>

Good luck with your project.:wink:

And don’t forget to like it, if you really liked it.

1 Like

Thank you very much @russian-dima
I’ll definitely try this and update you the status. I will start learning to code.
Thank you

@russian-dima I changed the color to white but still the I frame appears blank :neutral_face::neutral_face::neutral_face:

Ok, i would suggest you first to get more informations about JS & HTML-programming. Generating more complex things, without any knowledge is almost impossible.

To understand all these things you will surely need more then a half a year or even more, to be able to handle the coding.

Please learn more JS, HTML and even CSS-coding.

Here you will find all informations you will need…
https://www.w3schools.com/
and also take a look onto …
https://www.wix.com/velo/reference/api-overview/introduction

It’s now on you how much time, interest and effort you will give to learn the whole programming-stuff to realize your wished project.

Also do not forget to take a look onto the many given post here in this VELO-forum.

Do everything step by step.
-learn how to work with DATABASE and DATASET
-learn how to work with HTML-components
-learn basic JS-coding
-learn basic-HTML-coding
-perhaps even learn CSS-basic-coding.

When working with HTML-codes, you can use —> JS-Fiddle
https://jsfiddle.net/

1 Like

for all your support and quick replies. Could you please help me one last time with the code. I’m still getting a white blank iframe. I will use e resources you’ve shared.

OK! Then one more time…

First i want to understand properly what you want to achieve?

  1. What is your aim? What do you want to create?
  2. How should it work?
  3. Which kind of html-code do you have in your DB-field (“html2”) ?


Please expand the html2-field, so the whole html-code is visible.

  1. Do you use a dataset? If so, which one? —> Dynamic or non-dynamic?
    Here you are talking about “dynamic-dataset”…


…but why you use query instead of following my last postet example, which shows a —dataset-example?

It would be the best, if you first would try to explain one more time in detail, what you want to generate with the help of an HTML-Component? And also show your current code and project-setup.

I need first a good overview to be able to help you.

Something like…

  1. I am using a dynamic dataset (ID = “dataset1”)

  2. I have an html-component (ID="html16)

  3. I have a DATABASE/COLLECTION (ID = “Properties”)

  4. I have a DATAFIELD in my DB called —> “html2” where i store my HTML-CODE.

  5. The html-code is for…??? My idea is…???

  6. …and so on…

  7. This is my current code…

import wixData from'wix-data'; 

$w.onReady(()=>{ 
    wixData.query("Properties").find().then((results)=>{
 if(results.items.length >0){
 let firstItem = results.items[0]; console.log("First-Item: ", firstItem)
 let items = results.items; console.log("Items: ", items)
 
           console.log(items[0].html2)
           console.log(items[1].html2)
           console.log(items[2].html2)
           console.log(items[3].html2)
           $w("#html1").postMessage(items); //<---- send DATA to ---> HTML-component
 }
 else{}
 }).catch((err)=>{let errorMsg = err; console.log(errorMsg)});
});

HTML-CODE:

<!doctype html>
<html>
<head>
 <script type="text/javascript">
 function load_Message() {
            window.onmessage = (event) => {
 if(event.data) {
                    console.log(data[0].html2)
                    console.log(data[1].html2)
                    console.log(data[2].html2)
                    console.log(data[3].html2)
                    document.getElementById("xxxxx").innerHTML = event.data.cxCode;
 }
 }
 }
 
 </script>
</head>
<body onload="load_Message();" style="background-color:#ff0fff;">
<div id="xxxxx">
 <p id="sss"></>
</div>
</body> 
  1. This are all related datafields, which are used in this little project… and so on…

When i understood your idea, i sure can help you better.

1 Like

Hello @russian-dima . I will try to explain my project. My aim is to display a pdf document with annotation features. For that I use a service from Adobe called Adobe PDI Embed API. That generates an html code for me (ref. 4).

  1. I am using a dynamic dataset (ID = “dynamicDataset”)

  2. I have an html-component (ID=“html16”)

  3. I have a DATABASE/COLLECTION (ID = “Properties”)

  4. I have a DATAFIELD in my DB called —> “adobepdf” with fieldkey “adobepdf” that is a “Text” field where I store my HTML-CODE that I get from the Adobe PDF Embed API

The code is

<div id="adobe-dc-view"></div>
<script src="https://documentcloud.adobe.com/view-sdk/main.js"></script>
<script type="text/javascript">
	document.addEventListener("adobe_dc_view_sdk.ready", function(){ 
		var adobeDCView = new AdobeDC.View({clientId: "ac7e4b6ae93e405d8b03cc5cb95565c4", divId: "adobe-dc-view"});
		adobeDCView.previewFile({
			content:{location: {url: "https://dl.dropboxusercontent.com/s/w2ljsa1exr523v0/Reading%20FT1.pdf"}},
			metaData:{fileName: "Reading FT1.pdf"}
		}, {defaultViewMode: "FIT_WIDTH", showLeftHandPanel: false, showPageControls: false, 
			showDownloadPDF: false, showPrintPDF: false});
	});
</script>
  1. The html-code is for displaying a PDF. My idea is to make user read the content from the pdf and they are also able to highlight the text from the pdf.

  2. The code in the iframe is the one that you provided

<!doctype html>
<html>
<head>
    <script type="text/javascript">
        function load_Message() {
            window.onmessage = (event) => {
                if(event.data) {
                    console.log(data[9].adobepdf)
                    console.log(data[10].adobepdf)
                    console.log(data[11].adobepdf)
                    console.log(data[12].adobepdf)
                    document.getElementById("xxxxx").innerHTML = event.data.cxCode;
                }
            }
        }
 
    </script>
</head>
<body onload="load_Message();" style="background-color:#ffffff;">
<div id="xxxxx">
    <p id="sss"></>
</div>
</body>  

what should I replace the highlighted text with ?

The page code is

import wixData from'wix-data'; 
$w.onReady(()=>{ 
    wixData.query("Properties").find().then((results)=>{
 if(results.items.length >0){
 let firstItem = results.items[0]; console.log("First-Item: ", firstItem)
 let items = results.items; console.log("Items: ", items)
 
           console.log(items[9].adobepdf) //<--- the item no. where the iframe code is stored in the dataset and there are 4 more such ID like 10, 11 , 12, 13 and that code must be displayed on other such dynamic pages.
 
           $w("#html6").postMessage(items); //<---- send DATA to ---> HTML-component
 }
 
 }).catch((err)=>{let errorMsg = err; console.log(errorMsg)});
});


This is pretty much everything about the project.

Hope this gives you an idea of what exactly I wanna do

Thank you once again for your support

I think this here was the PDF-Site which you have used…
https://www.adobe.io/apis/documentcloud/dcsdk/docs.html?view=view

https://www.adobe.io/apis/documentcloud/dcsdk/pdf-embed.html

Is this what you want to achieve?
https://www.media-junkie.com/pdf-test
???

What you will need to do ?

  1. Create a PDF-Collection (already done by you —> “Properties”)
  2. Collection—> title -----> insert here the name of your PDF
  3. Collection—> pdfUrl → insert here the URL of your PDF
  4. Connect a —> DATASET to your Collection (“dataset1”)

Your collection should now look like…(in my example called —> “PDF-DATA”)


SITE-CODE:

$w.onReady(async()=>{
    let DATASET = '#dataset1'; console.log(DATASET)
    $w(DATASET).onReady(async()=>{//console.log($w(DATASET).getCurrentItem())
       let length = await $w(DATASET).getTotalCount();
       let pdfURL  = await $w(DATASET).getCurrentItem().pdfUrl; 
       let pdfTITLE= await $w(DATASET).getCurrentItem().title;
       let tokenID = "ac7e4b6ae93e405d8b03cc5cb95565c4";    
       let divID   = "adobe-dc-view"; 
       
       let pdfDATA = {
          "pdfURL":   pdfURL,
          "pdfTITLE": pdfTITLE,
          "tokenID":  tokenID,
          "divID":    divID
       }
       console.log("Data-Length: ", length); 
       console.log("PDF-URL: ", pdfURL); 
       console.log("PDF-Title: ", pdfTITLE); 
       console.log("Token-ID: ", tokenID);                
       console.log("Div-ID: ", divID) 
       console.log("DATA: ", pdfDATA)
       $w("#html1").postMessage(pdfDATA);
 });
});

HTML-CODE:

<html>
  <head>
    <title>PDF-TEST</title>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
  <meta id="viewport" name="viewport" content="width=device-width, initial-scale=1"/>
  
    <script src="https://documentcloud.adobe.com/view-sdk/main.js"></script>
    <script type="text/javascript">
      	function load_Data(){
          window.onmessage = (event) => {
            if(event.data) {console.log(event.data)
              console.log("Token-ID: (HTML) ",  event.data.tokenID);
              console.log("Token-ID: (HTML) ", event.data.divID);
              console.log("PDF-Title: (HTML) ", event.data.pdfTITLE); 
              console.log("PDF-URL (HTML): ", event.data.pdfURL); 

              var adobeDCView = new AdobeDC.View({
                clientId: event.data.tokenID, divId: event.data.divID});
            	adobeDCView.previewFile({content:{
                location:{url: event.data.pdfURL}}, metaData:
                {fileName:event.data.pdfTITLE}});
            }
            else {console.log("No data found.")}
          }
        }
    </script>
    </head>
    <body onload="load_Data();" style="background-color:#ff00ff;">
      <div id="adobe-dc-view"></div>
    </body>
</html>
1 Like

@russian-dima there are few things I would like to explain.

  1. Adobe pdf embed api is a tool that displays my pdf through a source url ( cloud location where the url is stored) so basically Adobe is only a facilitator that allows my pdf to be displayed by embedding a code( stored in my datafield the html code)

  2. If I directly use the url, when the page load in the live version my pdf get downloaded automatically.

  3. I want my user to read the pdf on my website without able to download the file.

  4. Meanwhile I will try the method which have shared.
    Thank you very much