I am trying to change the content of an html page when some action on the widget is taken.
Code:
function widget(newURL) {
var server_url = "127.0.0.1:8000";
var oldHTML = document.documentElement.innerHTML;
$.post(server_url + "/convert/",
{ input_html: oldHTML, convert: newURL },
function(response) {
var resp = JSON.stringify(response);
resp = resp.substring(1, resp.length - 1);
var jObj = JSON.parse(resp);
var win = window.open(newURL,'_self');
document.write(jObj.data);
});
}
With this code, though the HTML content gets changed but the HTML page's URL doesnot change. Can someone please suggest how can i change webpage URL as well as content both ?
Updated Code:
function widget(newURL) {
var server_url = "127.0.0.1:8000";
var oldHTML = document.documentElement.innerHTML;
$.post(server_url + "/convert/",
{ input_html: oldHTML, convert: newURL },
function(response) {
var resp = JSON.stringify(response);
resp = resp.substring(1, resp.length - 1);
var jObj = JSON.parse(resp);
window.history.pushState({"html":jObj.data},"", newURL);
document.documentElement.innerHTML = jObj.data;
});
}
In the updated Code, the URL changes as well as the content.
Thanks,
Try window.history :
window.history.pushState({"html":jObj.data,"pageTitle":'Hello'},"", newURL);
document.documentElement.innerHTML = jObj.data;
Take a look at this answer.
hope this helps.
Related
Below is the code for the popup.js in my chrome extension v3
The parts I commented out are meant to extract previews (of the first few lines) for the respective queries, but when implemented, the search for the extension does not work at all (no errors though).
I tried logging into console to see what happened along the way, and noticed that even the response object did not register anything in the console, needless to say the HTML. Any clues, or perhaps there are better ways to generate the previews?
document.addEventListener("DOMContentLoaded", function () {
// Select the search form and the search results container
var form = document.getElementById("search-form");
var container = document.getElementById("search-results");
// Handle the submit event of the form
form.addEventListener("submit", function (event) {
event.preventDefault(); // Prevent the form from being submitted
// Get the search title from the form
var title = form.elements.title.value;
var title2 = title.replace(/ /g, "+"); // Replace spaces with +
var results = [];
var queries = [
{
url: `https://www.ncbi.nlm.nih.gov/pmc/?term=${title}`,
title: "NCBI PMC"
},
{
url: `https://www.biorxiv.org/search/${title}`,
title: "bioRxiv"
},
{
url: `https://www.medrxiv.org/search/${title}`,
title: "medRxiv"
},
{
url: `https://www.google.com/search?q=${title2}+filetype:pdf`,
title: "PDF Search"
}
];
queries.forEach(function (query) {
fetch(query.url)
.then(function (response) {
return response.text();
console.log(response);
})
// .then(function (html) {
// console.log(query.title);
// console.dir(html); // Inspect the properties of the html variable
// console.table(html); // View the contents of the html variable as a table
// // Parse the HTML using the DOMParser
// var parser = new DOMParser();
// var doc = parser.parseFromString(html, "text/html");
// // Extract the relevant information from the parsed HTML
// var title = doc.querySelector("title").innerText;
// var lines = [];
// var paragraphs = doc.querySelectorAll("p");
// for (var i = 0; i < paragraphs.length; i++) {
// lines.push(paragraphs[i].innerText);
// if (lines.length === 5) {
// break; // Break the loop
// }
// }
results.push({
title: query.title,
url: query.url,
// preview: lines.join("\n")
});
// });
});
// Create the search results HTML
var resultsHTML = "";
results.forEach(function (result) {
resultsHTML += `<div class="result">
<h2>${result.title}</h2>
<p>${result.preview}</p>
</div>`;
});
// Update the container with the search results HTML
container.innerHTML = resultsHTML;
// Handle the click event of the result links
container.addEventListener("click", function (event) {
var target = event.target;
if (target.tagName === "A") {
// Open the URL in a new tab and bring it to the front
var url = target.dataset.url;
var tab = window.open(url, "_blank");
tab.focus();
}
});
});
});```
I have a qr-code button. On click, qr-code is generated and dialog to save the image format pops-up. In which the filename always comes as "qrcode.png". I have to dynamically change the filename to the name of the files from where the qr-code is generated.
Please, help. I am new to this technology.
HTML TWIG
<th data-field="QR-BTN" data-width="60px" data-orderable="false">{{ 'QR'|trans }}</th>
JAVASCRIPT
var QREXPORT = (function() {
var qrCodeExport = function (e){
e.preventDefault();
//goqr.me api url
const QRCODE_API_URL = "https://api.qrserver.com/v1/create-qr-code/?"; //Library Used
var $form = $('#modal-qr-export-offering'),
qrFormat = $("input[name='qrCodeType']:checked").val(),
jsFormData = $form.data('bs.modal'),
accessCode = jsFormData.options.accesscode;
var params = {
data: "SESSION-" + accessCode,
size: "250x250",
margin: 0,
download: 1,
format: qrFormat,
};
window.location.href = QRCODE_API_URL + $.param(params);
};
return {
init: function() {
$(document).ready(function(){
$('#radioSvg').prop('checked', true);
$('#modal-qr-export-offering').on('hidden.bs.modal', function() {
location.reload();
});
});
$(document).on('click', '.js-btn-submit-form', qrCodeExport);
}
};
})();
QREXPORT.init();
Try using the a tag with download attribute...?
const linkEl = document.createElement('a')
linkEl.href = QRCODE_API_URL + $.param(params);
linkEl.download = 'download-name-here.png'
document.body.appendChild(linkEl)
linkEl.click()
// Maybe remove the link after it worked...?
linkEl.remove()
I am creating a chrome extension which access a api and parses the json feed to get data. One of the data is a link and I want the link to be opened in a new tab. I use chrome.create.tabs to do it. But instead of opening a tab with specified url it opens like this
chrome-extension://app_id/%22http://www.twitch.tv/imaqtpie%22
Here is my popup.js
document.addEventListener('DOMContentLoaded', init);
function init(){
var elem = document.getElementById('Add');
elem.addEventListener('click',func);
}
function func(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.twitch.tv/kraken/search/streams?q=league%20of%20legends", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// innerText does not let the attacker inject HTML elements.
var qtpie=JSON.parse(xhr.responseText);
var display_name = JSON.stringify(qtpie.streams[0].channel.display_name);
var stream_status = JSON.stringify(qtpie.streams[0].channel.status);
var stream_url=JSON.stringify(qtpie.streams[0].channel.url);
var res = display_name+" : "+stream_status+"\n"+stream_url;
console.log(stream_url);
var a = document.createElement('a');
var linkText = document.createTextNode(res);
a.appendChild(linkText);
a.setAttribute('href', stream_url);
a.addEventListener('click', link_handler(stream_url));
document.getElementById("status").appendChild(a);
var magic=activateLinks();
// document.getElementById("status").innerText = res;
}
}
xhr.send();
}
function activateLinks()
{
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
(function () {
var ln = links[i];
var location = ln.href;
ln.onclick = function () {
chrome.tabs.create({active: true, url: location});
};
})();
}
}
function link_handler(url)
{
// Only allow http and https URLs.
if (url.indexOf('http:') != 0 && url.indexOf('https:') != 0) {
return;
}
chrome.tabs.create({url: url});
}
Here stream_url is the variable that stores the parsed url from json.
here is the json from which it is parsed from
"video_banner":null,
"background":null,
"profile_banner":null,
"profile_banner_background_color":null,
"partner":true,
"url":"http://www.twitch.tv/imaqtpie",
"views":91792487
i want the new tab to open http://www.twitch.tv/imaqtpie instead of chrome-extension://app_id/%22http://www.twitch.tv/imaqtpie
. Thanks in advance. Btw using <base href="http://" target="_blank"> does not work.
So the problem is for the url. Your url is improper when using chrome.tabs.create, because %22 indicates the character " in ASCII Encoding Reference. You should strip it off in the url when you get the element in html. Glad it helps!
i have soure code :
$("#yes-modal").click(function (e) {
var img = $("#url").val();
window.location = '#Url.Action("DownloadImages", "Hrd", new { id = *value variable img* })';
});
i want get value img, but i have error.
How can do it ? thank you.
Below syntax should work.
window.location = '#Url.Action("DownloadImages", "Hrd", new { id = ' + img + '})';
Let me know if you face any issue.
The razor syntax is a serverside code. It is evaluated while rendering the page from server. But the javascript is evaluated at the client side (browser). So you have to split it like below code.
$("#yes-modal").click(function (e) {
var img = $("#url").val();
var loc = '#Url.Action("DownloadImages", "Hrd")';
var loc += '?id=' + img;
window.location = loc;
});
Hello there i got some code here;
<script type="text/javascript">
$(function(){
var playListURL = 'http://gdata.youtube.com/feeds/api/playlists/8BCDD04DE8F771B2?v=2&alt=json&callback=?';
var videoURL= 'http://www.youtube.com/watch?v=';
$.getJSON(playListURL, function(data) {
var list_data="";
$.each(data.feed.entry, function(i, item) {
var feedTitle = item.title.$t;
var feedURL = item.link[1].href;
var fragments = feedURL.split("/");
var videoID = fragments[fragments.length - 2];
var url = videoURL + videoID;
var thumb = "http://img.youtube.com/vi/"+ videoID +"/default.jpg";
HERE>>> list_data += '<button onclick="$('#bgndVideo').changeMovie('+ url +')">'+ feedTitle +'</button>';
});
$(list_data).appendTo(".playlist_elements");
});
});
</script>
This isnt working because of "$('#bgndVideo')" fragment that i need to pass as a text to be rendered in html so it looked like this in html:
<button onclick="$('#bgndVideo').changeMovie('http://www.youtube.com/watch?v=SOME_VIDEO_ID')"> Test </button>
How could i fix this so "$('#bgndVideo')" fragment would be treated as a text?
You would need to escape the 's:
list_data += '<button onclick="$(\'#bgndVideo\').changeMovie(\''+ url +'\')">'+ feedTitle +'</button>';
However, a cleaner approach might be something like this:
$list_data = $("<button>").html(feedTitle)
.click(function(){
$('#bgndVideo').changeMovie(url);
});