problem of getting url of loading html page (c#) - javascript

Well,
I develop a native browser and i've got a problem with a site navigated on this browser.
An input["type"]-button click post an httprequest to obtain and show an other page in a new tab (onglet).
I'm trying several methods but the TabPageof webBrowser is blank and I've got a IE explorer window opening.
here the code
private void Browser_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
{
webBrowser22 = (WebBrowser)sender;
if (webBrowser22.Document != null)
{
foreach (HtmlElement tag in webBrowser22.Document.All)
{
HtmlElementCollection elements = webBrowser22.Document.GetElementsByTagName("input");
for (int i = 0; i < elements.Count; i++)
{
HtmlElement el = elements[i];
string elType = el.GetAttribute("type");
switch (elType)
{
case "radio":
case "checkbox":
case "button":
{
el.MouseUp += new HtmlElementEventHandler(link_MouseUpPup);
}
}}}}
private void link_MouseUpPup(object sender, HtmlElementEventArgs e)
{
this.tb2 = new System.Windows.Forms.TabPage();
this.webBrowser221 = new System.Windows.Forms.WebBrowser();
var linky = (HtmlElement)sender;
mshtml.HTMLAnchorElement ba = (mshtml.HTMLAnchorElement)linky.DomElement;
// if ((ba.target != null && ba.target.ToLower() == "_blank") || e.ShiftKeyPressed || e.MouseButtonsPressed == MouseButtons.Middle)
//if (Regex.Match(e.ReturnValue.ToString(), "http:").Value != null || Regex.Match(e.ReturnValue.ToString(), "https:").Value != null)
tabControl1.Controls.AddRange(new Control[] { this.tb2 });
tb2.Controls.AddRange(new Control[] { this.webBrowser221 });
webBrowser221.Dock = DockStyle.Fill;
1ERE METHODE----
//webBrowser221.Navigate(HttpContext.Current.Request.Url.AbsoluteUri);
2EME METHODE----
//webBrowser221.Navigate(ba.href);
3EME METHODE----
// webBrowser221.Navigate(HttpContext.Current.Request.ServerVariables["URL"].ToString());
4EME METHODE----
// webBrowser221.Navigate(e.ToElement.GetAttribute("onclick").ToString());
tb2.Text = e.ToElement.GetAttribute("onclick").ToString();
tb2.ToolTipText = webBrowser221.StatusText;
}
The problem is that I would opening the site page loading by the click input after his process (the process is been programmed in html and javascript with the function window.open and the property target="_blank") by the c# control webBrowser.
who's the problem, it's ie explorer that is opening instead of webBrowser window.
thanks your for your help.
M.A.

Finally,
I used the package reference "SHDocVm" of "Microsoft Internet Controls" and I place a function handler NewWindow3 after the case button and it's ok, a window.open() javascript function with target="_blank" opens a new page of webBrowser.
Truly yours.
M.A.

Related

firefox addon: cannot update tab URL using web extension

I'd like to know how to update URL addresses in Firefox using Web Extensions.
I'm trying to port a simple extension I've created with Chrome APIs to Firefox, but I don't really understand the tab URL mechanisms in Firefox.
This extension was made to switch between YouTube desktop/TV version with a click.
It works well on Chrome, but I don't know why it's not working on Firefox.
UPDATE 1: Placing most important code block related to the question:
chromeApi.browserAction.onClicked.addListener(function(tab) {
var actionUrl = '';
var tabUrl = tab.url;
if (getCurrentPageVersion(tabUrl) !== undefined) {
actionUrl = getConvertedActionUrl(tabUrl);
if (actionUrl !== tabUrl) {
chromeApi.tabs.update(tab.id, {url: actionUrl});
}
}
});
Full source
(function(chromeApi) {
getCurrentPageVersion = function (tabUrl) {
var ytValidRegex = /^(https?\:\/\/)?(www\.)?(youtube\.com|youtu\.?be)/g;
var ytValidStdPageRegex = /^(https?\:\/\/)?(www\.)?(youtube\.com|youtu\.?be)?(\/watch\?v=).+$/g;
var ytValidTvPageRegex = /^(https?\:\/\/)?(www\.)?(youtube\.com|youtu\.?be)?(\/tv#\/watch(\/video)?\/(idle|control)\?v=).+$/g;
if (!ytValidRegex.test(tabUrl)) {
return undefined;
} else if (ytValidStdPageRegex.test(tabUrl)) {
return "std";
} else if (ytValidTvPageRegex.test(tabUrl)) {
return "tv";
}
return undefined;
};
getConvertedActionUrl = function (tabUrl) {
var result = '';
var shortStdYtUrlRegex = /\/watch\?v=.+/g;
var shortTvYtUrlRegex = /\/tv#\/watch\/video\/(idle|control)\?v=.+/g;
var shortStdYtUrlReplaceRegex = /\/watch\?v=/g;
var shortTvYtUrlReplaceRegex = /\/tv#\/watch\/video\/(idle|control)\?v=/g;
if (shortStdYtUrlRegex.test(tabUrl)) {
result = tabUrl.replace(shortStdYtUrlReplaceRegex, '/tv#/watch/idle?v=');
}
else {
result = tabUrl.replace(shortTvYtUrlReplaceRegex, '/watch?v=');
}
// YouTube standard website video url
//https://www.youtube.com/watch?v=9tRDQK2MtRs
// YouTube TV url
//https://www.youtube.com/tv#/watch/video/idle?v=9tRDQK2MtRs
return result;
}
onInit = function () {
};
// Called when the user clicks on the browser action.
chromeApi.browserAction.onClicked.addListener(function(tab) {
var actionUrl = '';
var tabUrl = tab.url;
if (getCurrentPageVersion(tabUrl) !== undefined) {
actionUrl = getConvertedActionUrl(tabUrl);
if (actionUrl !== tabUrl) {
chromeApi.tabs.update(tab.id, {url: actionUrl});
}
}
});
chromeApi.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
if(!changeInfo.url) return; // URL did not change
// Might be better to analyze the URL to exclude things like anchor changes
var pageVersion = getCurrentPageVersion(tab.url);
if (pageVersion === undefined) return;
/* ... */
chromeApi.browserAction.setBadgeText({text: pageVersion.toUpperCase(), tabId: tab.id});
});
chromeApi.tabs.onCreated.addListener(function(tab){
var pageVersion = getCurrentPageVersion(tab.url);
if (pageVersion === undefined) return;
/* ... */
chromeApi.browserAction.setBadgeText({text: pageVersion.toUpperCase(), tabId: tab.id});
});
})(chrome);
If you pay attention, the core functionality happens on the chromeApi.browserAction.onClicked event, whenever you click the add-on/extension button.
The extension updates correctly between each YouTube version in Chrome, but in Firefox, this one redirects to YouTube TV once and never goes back to the desktop version no matter how many times you click on it.
But there's something weird in Firefox: browser history is updated correctly whenever the tab.update method is called, but it redirects to the TV version by itself again.
IMPORTANT: Both Firefox/Chrome extensions are using the currentTab permission, so it's not an extension issue by itself.
Extension on GitHub
UPDATE 2 (2018-11-25): I've updated the source code based on previous feedback

background.js is no longer accessible after iframe is loaded in background.html

In background.js, I injected an iframe:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.action == "doubanSearch")
test(request.title, request.year);
}
);
function test(title, year){
var frame = document.createElement('iframe');
frame.src = 'https://movie.douban.com/subject_search?cat=1002&search_text=' + title + ' '+ year;
document.body.appendChild(frame);
}
However, once the iframe is loaded, the background.js no longer responds to doubanSearch request. Is there a solution to allow background.js remain responsive to future requests even iframe is loaded?
I have checked the content.js separately and can confirm it does what I want it to be doing.
update 1
The netflixContent.js that makes requests:
var prevDOM = null;
var prevMovieTitle = 'prevMovie';
// Mouse listener for any move event on the current document.
document.addEventListener('mousemove', function (e) {
var srcElement = e.srcElement;
if (srcElement == null)
return;
if (prevDOM != srcElement){
prevDOM = srcElement;
return;
}
// find the bob-overlay class
if (srcElement.parentElement != null && srcElement.parentElement.className.startsWith('bob')) {
while (srcElement.className!="bob-overlay"){
srcElement = srcElement.parentElement;
// if srcElement is no longer a bob- class, we are out of luck here.
if (srcElement == null || !srcElement.className.startsWith('bob'))
return;
}
}
// the srcElement at this stage has to be bob-overlay class!
if (srcElement == null || srcElement.className!="bob-overlay")
return;
// now we are in the right place, get movie title and publication year
var movieTitle = srcElement.getElementsByClassName('bob-title');
var movieYear = srcElement.getElementsByClassName('year');
if (movieTitle.length != 1){
console.log('Movie title not found.', srcElement);
return;
}
if (movieYear.length != 1){
console.log('Movie year not found.', srcElement);
return;
}
// now get the title and year
movieTitle = movieTitle[0].textContent;
movieYear = movieYear[0].textContent.trim();
// if the current movie is the same as the previous movie, we return.
if (movieTitle == prevMovieTitle)
return;
// return if title is empty
if (movieTitle == '')
return;
// if movie year isn't empty, add parenthesis.
if (movieYear != '')
movieYear = '(' + movieYear + ')';
prevMovieTitle = movieTitle;
console.log('Movie found:', movieTitle, movieYear);
// replace special characters with space.
movieTitle = movieTitle.replace(/[^\w\s]/g, ' ').trim();
console.log('Movie found (special characters removed) :', movieTitle, movieYear);
// now let's send the message and start searching!
chrome.runtime.sendMessage({action: 'doubanSearch', title: movieTitle, year: movieYear});
}, false);
It is opensource hosted on github in case you need to check out the entire code. I'm really new to js and chrome extension development, so please execuse me for crappy coding :).
update 2
The background page before a request is sent:
The background page after a request is sent and iframe is loaded
Also, the background page link is no longer available from the chrome://extensions:
The site performs frame-busting (assigning top.location to an URL of the page itself) which navigates the background page to the site URL so the extension no longer has a background page. It looks like an oversight in Chrome which has been intermittently prevented in some recent versions and is about to be fixed for good in v67.
The solution is to sandbox the iframe by adding the following attribute:
frame.sandbox = 'allow-scripts';
Some sites may require more features to be allowed e.g. allow-forms, see MDN for the full list.

Redirect to a page after a pop up opens

I am trying to redirect a web page after a condition is returned as true but I can't seem to get it work. In theory this should, shouldn't it. What am I missing, is it even possible!
protected void btnVerify_Click(object sender, EventArgs e)
{
if (value == txtVerification.Text || txtVerification.Text == "****")
{
//defines a bool to tell if the popup window has been shown, this will only ever return true
bool PopupShown = doRedirect();
if(PopupShown)
{
Response.Redirect("somewebpage.aspx");
}
}
else
{
lblVerificationFailed.Visible = true;
}
}
//Opens the popup window to fire off the download and returns true
bool doRedirect()
{
string url = "GetDocs.aspx";
string s = "window.open('" + url + "', 'GetDocs', 'height=150,width=300,left=100,top=30,resizable=No,scrollbars=No,toolbar=no,menubar=no,location=no,directories=no, status=No');";
ClientScript.RegisterStartupScript(this.GetType(), "script", s, true);
return true;
}
You are trying to do in the server things that can be much more easily done on the client side.
You're using a server event to catch the click of a button on your view, launch a client popup and later redirect your page execution.
Try with something like this on javascript:
var btnVerify = document.getElementById("btnVerify");
btnVerify.addEventListener("click", function() {
window.open('GetDocs.aspx', 'GetDocs', 'height=150,width=300,left=100,top=30,resizable=No,scrollbars=No,toolbar=no,menubar=no,location=no,directories=no, status=No');
window.location.href = "somewebpage.aspx";
});
Sussed it, if I use window.location.replace instead of window.location it works exactly like I want it to. Many thanks all :)

Chrome extension logic is not wοrking

I've managed to get most of my Chrome extension working, but there is a problem I can't work out.
You can grab it here if you want and load it as an unpacked extension.
After loading it works like this.
You are prompted that they need to enter a URL on the options page.
You enter a URL (e.g. http://example.com) on the options page as asked and click save, and then when you click the icon in the toolbar you can see the web page appear in the popup.
If you then go and removes the URL from the options page and clicks save, then the popup does not show the original prompt page they saw at the beginning.
I think this code (from popup.js) is at fault, but I can't see why it won't work.
var url = localStorage.url;
var alturl = chrome.extension.getURL("need-to-enter-url.html");
var element = document.getElementById("testerURL");
if (url != undefined || url != null) {
element.src = url;
} else {
element.src = alturl;
};
When you "remove" the url you are actually saving an empty string. localStorage.url = "" so your value checking is failing. I would also recommend tweaking the if logic to be clearer.
Use something like this:
if (url === undefined || url === null || url === "") {
element.src = alturl;
} else {
element.src = url;
}
Optionally you can rely on JavaScript's truthiness.
if (url) {
element.src = url;
} else {
element.src = alturl;
}

Chrome Extension change div content of a local page

I have a local html page called "PageRedirect.html" for chrome extension that has a p tag with id called "toChange"
I have a function in background.js
function doRedirect(tab,val){
var tabUrl = encodeURIComponent(tab.url);
var tabTitle = encodeURIComponent(tab.title);
// determine the type of redirection
if(val == 1 ){
var redirectURL = chrome.extension.getURL('PageRedirect.html');
}
chrome.tabs.update(tab.id, {url: "redirectURL"});
}
This will successfully redirect the page I want.
However, if I want to dynamically p tag with id="toChange" content from blank to new string that I want.
What can I do in this case?
Is there any demo?
I tried message sending method but it has some problems locating the id.
Something like this
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse)
{
if (request.warning == "true"){
url = request.url;
var elem = document.getElementById("toChange"); // elem will be undefined
}
}
);
I am guessing the reason why it will be undefined is caused by the fact that PageRedirect.js is not the "document".

Categories

Resources