0

How to include product url in Custom js file,

In Magento2.

I am using below code in template file:

$_product = $block->getProduct();
$_product_url= $_product->getProductUrl();
echo $_product_url;

How to use it in js file

  • Can you explain little bit more? where you want to add product url? – Amit Naraniwal Mar 5 at 12:34
  • Do you need product url in custom js file from product detail page ? – user55548 Mar 5 at 12:34
  • Yes, from product detail page – shivashankar m Mar 5 at 12:37
  • please find the updated question – shivashankar m Mar 5 at 12:39
1

Add following code on product page

<input type="hidden" name="product_url" id="product_url" value="<?php echo  $_product_url ?>" />  

Then get this hidden filed value in your custom javascript as follow

var productUrl = document.getElementById('product_url').value;

Please let me know still if you have any question.

  • Thanks @user55548 is that above code will work in custom.js file – shivashankar m Mar 5 at 12:43
  • my file is not template file – shivashankar m Mar 5 at 12:43
  • Put hidden field code you any phtml file which is use on product detail page. eg. put code in addtocart.phtml or gallery.phtml. Just make sure that code should be after crate product object. Then you can fetch value in javascript of that hidden filed. – user55548 Mar 5 at 12:47
  • Put your code in hidden filed like <input type="hidden" name="product_url" id="product_url" value="<?php echo $_product_url ?>" /> In your custom js file var productUrl = document.getElementById('product_url').value – user55548 Mar 5 at 12:56
  • Thanks a lot @user55548 its working fine. – shivashankar m Mar 6 at 17:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.