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

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

1 Answer 1

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.

8
  • Thanks @user55548 is that above code will work in custom.js file Mar 5, 2019 at 12:43
  • my file is not template file Mar 5, 2019 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, 2019 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, 2019 at 12:56
  • Thanks a lot @user55548 its working fine. Mar 6, 2019 at 17:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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