0

I am setting a url to a DOM of a website. Now I could done it by copying the actual url, as below:

document.getElementById('mediaWebUrl').setAttribute('value','https://www.youtube.com/watch?v=hkOTAmmuv_4');

It is not convenient enough. I want to substitute the actual url with a variable. like below:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
     var activeTab = tabs[0];
     var videoUrl = activeTab.url; // or do whatever you need    
  });

But when I do the job as below:

document.getElementById('mediaWebUrl').setAttribute('value',videoUrl);

it didn't succeed and nothing happened. Why? I confirmed the type of the variable "videoUrl" is a string using alert(typeof videoUrl). As neophyte in Javascript, I really need advice in this simple question. Thank you.

Rachel Gallen
  • 27,943
  • 21
  • 72
  • 81
Wei Zhang
  • 325
  • 2
  • 16
  • I found this problem is simillar to get the return value of chrome APIs. It seems impossible unfortunately. https://stackoverflow.com/questions/33755163/how-to-force-chrome-tabs-query-returns-a-value. If anyone have better idea, I would like to know much. – Wei Zhang Jul 12 '19 at 05:30

1 Answers1

0

You can write a function and pass the value of the id of the div (where you want to display the video) and the video url, and then call the function to set the attribute.

Sample code:

function setVal(id, val){
    var el = document.getElementById(id); //get the element
    var attrVal = val; //set the url

    el.setAttribute('value', val) //set the value to the url

}

setVal("myVid", "https://www.youtube.com/watch?v=hkOTAmmuv_4"); //call the function 
(in this case, myVid is the id)

Your code probably didn't worked because the variable was only locally defined. You can use your web console to check for errors.

Hope this helps!

Rachel Gallen
  • 27,943
  • 21
  • 72
  • 81
  • I think the error reason is the locally defined. Could I define a output variable or return value? Like url0=chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { ...return videoUrl}) . Could this be a solution? – Wei Zhang Jul 12 '19 at 03:24
  • It's half 4 am here. You can adapt any way you see fit. Use window location? Have to catch some winks. Hope the answer helped somewhat. . – Rachel Gallen Jul 12 '19 at 03:29
  • The sample code points out the problem, but I could not solve the problem with it. I could not get out the url from chrome.tabs.query command. Since the "setAttribute" function is used under another webpage, I could not use a nest function either. The problem is still confusing me. Thank you. – Wei Zhang Jul 12 '19 at 05:23
  • You can set a var (outside the function) like ``var vidUrl ="https://www.youtube.com/watch?v=hkOTAmmuv_4"`` and then call the function as ``setVal ("myVid", vidURL);`` Your main problem was that your var was defined locally instead of globally. Hope you get it working. – Rachel Gallen Jul 12 '19 at 11:12