How to make WKWebView open a new url with a navigation action of .linkActivated? - wkwebview

Assuming I have some Javascript in my WKWebView that causes it to open a new URL using
window.location = 'http://example.com/resource'
When the WKNavigationDelegate.handle(_:decidePolicyFor:) method gets called, the navigationAction.navigationType is .other. I would like it to be .linkActivated instead, because .other is basically a catchall and I don't want to have to do a bunch of special processing for all of the possible scenarios that the .other navigation type implies.
Is there any way in Javascript to make the window open a new location and cause .linkActivated to be passed as the navigationType?

Related

Trigger a dialog box in background script

I have a chrome extension, where I periodically throw out an alert based on something.
The thing is that the default alert in Javascript is very ugly and I am trying to replace it with something more beautiful.
The problem is that currently the alert is triggered from the background script. Google doesn't allow us to include any external libraries in the background html.
Given this problem, how do I go about replacing the default alert with a more modern UI alert?
I was looking to replace the default alert with something like the SweetAlert.
My background.js currently looks like this:
// on some alarm trigger
function showpopup() {
console.log(" in show popuup");
console.log(Date());
alert("ugly alert");
}
I also explored the option of injecting another js file from my background file.
function showpopup() {
console.log(" in show popuup");
console.log(Date());
var s = document.createElement('script');
// added "script.js" to web_accessible_resources in manifest.json
s.src = chrome.extension.getURL('script.js');
s.onload = function() {
this.remove();
};
(document.head || document.documentElement).appendChild(s);
}
My script.js currently just calls an alert
alert("ugly alert now in script.js");
I am not able to figure out how to create my own dialog box in this javascript file script.js.
The problem is where your alert will be shown?
In an browser/OS dialog window? That's what alert() and friends do; as you see yourself, it's ugly and inflexible. In addition, it's technically challenging: it's an old mechanism that stops execution of JS code until closed, which can lead to API malfunctioning; Firefox WebExtensions specifically don't support calling this from the background page.
In the background page? By definition, it's invisible. You can add DOM nodes with an alert there, but you will not see it. Your problem isn't loading a library, your problem is where to display results.
(invisible, so no picture here!)
In the currently open tab? Hijacking an arbitrary page to show your own UI is hard, prone to break, would require draconian permissions with user warnings at install, won't always work. Wouldn't recommend.
In a fresh window? Possible (see chrome.windows API), but hardly "modern UI" at all (at least you can hide the URL bar).
In a browser action popup? Still not possible to trigger it to open in Chrome, so that's out.
The de-facto standard for informing the user about such things is the chrome.notifications API. It offers limited customization, but that's the "modern" approach considering that your extension has no UI surfaces already open at alert time.
You can insert your code into the tab content via
JS: chrome.tabs.executeScript()
CSS: chrome.tabs.insertCSS()
The second possibility would be to use a content script (content.js). But then you would have to use messaging to communicate between background.js and content.js.

Wait for chrome.tabs.update tab to finish loading

I'm trying to work on a chrome extension and am trying to clean up some of my code by relying on the sendMessage. However the callback function activates before the page has finished loading so in the case of a new tab, nobody receives and in the case of an existing tab the page that is being moved from is getting the message (but that isn't what I want). I've looked for other people asking about that problem with new tabs and there wasn't a clear answer, the best suggestion I've seen is to create a global variable and create a listener for tab loads and compare it against this global variable.
So the question is, is there a way to wait in the callback function until the page has loaded, or do I create an array of JS objects that contain the tab I'm waiting on and the information I want to send to that tab.
For reference here is the relevant code in the background javascript file.
chrome.tabs.sendMessage(tab.id, {info: "info"}, function(response)
{
//This line isn't used when I am navigating without changing tabs
chrome.tabs.create({url: response.info.linkUrl}, function(tab1)
{
chrome.tabs.update(tab1.id, {url: response.info.linkUrl}, function(tab2)
{
chrome.tabs.sendMessage(tab2.id, {info: "More Info"});
});
});
});
Otherwise I am able to confirm that all of my tab side code works, once my sendMessage was delayed enough for me to see that with my own eyes. My code is able to consistently make it past validation on the page being navigated away from, confirmed by checking document.url.
You can try injecting a second content script instead of a message.
It will execute in the same context as your other script.
Something along the lines of
chrome.tabs.executeScript(tab2.id,
{code: 'showInfo("More Info);', runAt: 'document_idle'}
);
where showInfo does the same as your message handler.
It's a bit of a hack and I'm not 100% sure the load order will be correct.
Other possible solutions are more complex.
For example, you can make the content script report back that it is ready and have a handler for that, for instance you can register a listener for onMessage in the background that waits for a message from that specific tab.id, sends "More Info" and then deregisters or disables itself.
Or, you could potentially switch to programmatic injection of your content script, which would let you control load order.

Open and pass data to a popup (new tab) from content script

I'm writing a chrome extension and have a question.
My extension has some .html page in it, let it be 'popup.html'. I inject a content script into some page and this script opens a 'popup.html' in a new tab with something like 'var p = window.open(chrome.extension.getURL('/popup.html'), "popup")', which works perfectly. Next, I need to pass some data to this window and I can't figure how to do it in a simple way.
For some reason I can't call child window's function from a content script with
var p = window.open(chrome.extension.getURL('/popup.html'), "popup");
p.foo(data);
In the console I see Uncaught TypeError: Cannot call method 'foo' of undefined message.
I can't pass data in a query string, because the data is simply too big.
Is there an elegant and simple way to pass data to such kind of window? I thought about messaging, but how do I effectively get tab ID of a newly opened window w/out using a background page?
Thanks a lot in advance.
UPD:
I tried to inverse the logic and get a data from parent window with 'window.opener.foo()' but in a newly opened tab window.opener returns null.
Ok, I found two solutions to my problem.
1) Add a background page, which opens a popup with chrome.tabs.create(). Then send a message from a content script to a background page, which re-sends it to a corresponding tab via chrome.tabs.sendMessage(). It looks a little ugly, but works.
2) A better one, w/out background page. Extension (popup) page creates a listener for long-lived connection. Then content script sends a message to this connection. A problem here is that a listener is not created right after the page is opened, so there should be a mechanism for a content script to wait until popup is loaded. It can be a simple setTimeout or a notification from popup via same long-lived connection.
If anyone has a better solution I'd gladly check it out as well.

switch to chrome extension page without the tabs permission

I'm writing an extension for chrome that shows a results page when a user enters a query from the popup.
I would like subsequent queries to use the existing results page rather than opening new ones.
I used chrome.extension.getViews({'type':'tab'}) to get the currently opened extension pages and to pass the query to a javascript function in the open page.
The issue I'm having is switching to that page without requiring the 'tabs' permission.
This snippet of code works well from the background page.
chrome.tabs.getCurrent(function(tab){
chrome.tabs.update(tab.id, {selected: true});
});
However, tabs.getCurrent requires the 'tabs' permission. Is there a way to do this without the tabs permission?
I could use chrome.tabs.update but I don't know how to get the tab id from the view object returned from chrome.extension.getViews.
I'm fairly certain this can't be done without the tabs permission. You have correctly identified that chrome.tabs.update is the function you need, but without the tabs permission, it can only operate on the currently selected tab by provifing a null tab ID argument. Since you can't supply tab IDs in chrome.tabs.update without permission, switching between tabs is not possible.
/edit: As appsilers mentioned, not really doable.
If you can instead use chrome.tabs.create() to open the required tab, it will also return its tab id upon creation.
Otherwise the only way is to plast a global inside the target context and use chrome.extension.getViews() to identify the target and call a focus-stealing function, like alert(). But I'd advise against, since it's more like a hack and there isn't really a guarantee this functionality will keep stable between builds.

jQuery Mobile - Dialogs without changing hash

I have a search dialog that I am popping up and filling with jquery templates. After they make a selection I set a value on the current page. As such I don't need hashTags or anything like that, I just need a pop-up dialog that I can open and close programatically. I am currently opening the dialog with
$.mobile.changePage(dialog, { transition: "slide", changeHash: false });
and closing it with
dialog.dialog('close');
However, in certain cases (when the page is navigated to), closing the dialog refreshes the current page.
Is there a better way to interact with this?
Update:
I think I figured out what is going on. So for some reason, jquery mobile usually keeps 2 pages loaded on the DOM - one of which is invisible, you can verify this by running $('[data-role=page]') in the console. One page is the page you're on, the other is the page that you initially navigated to. Not quite sure why they choose to do that, but there you have it.
So they treat dialogs as a page navigation with a different transition even if the dialog is already in the DOM. Therefore, if you go directly to the page and then trigger a dialog, modifying the current page and closing it works fine - because the original page is always loaded in the DOM. However if you go to another page, than navigate to the page that triggers the dialog, and THEN trigger the dialog it destroys the current page so that the pages in the DOM are the initial one and the dialog. In that case it reloads that dialog-launching page entirely and you never get a chance to make any modifications.
Jeez. How do I interact with the jqm dialog widget directly?
You can try two other things. Both should work:
1 set DomChache
How about overriding JQM to keep the page your are firing the dialog from in the DOM? The docs say you can set data-dom-chache and override cleaning the page from the DOM.
If it only happens when you load this page in via AJAX (vs. loading it directly) you could make DOM-keeping dependend on your trigger page having data-page-external, assign DOM-chache="true" only when the dialog is openend and remove it again once the dialog is closed.
2 override JQM
I had the same problem you described and got it to work like this (requires hacking into JQM though...):
// inside transitionPages function
if ( !$(toPage).jqmData('internal-page')
{fromPage.data( "page" )._trigger( "hide", null, { nextPage: toPage } );}
}
My problem was that pagechanging to certain pages (same as dialog) caused the preceding page (where the dialog fired from) to be removed from the DOM, so I had a blank screen (when trying to go back). I added data-internal-page="true" to the pages, which should keep the preceding page intact and added the if-clause in JQM.
So now pageHide (and DOMcleanup) only fires, if I'm not going to a page labelled with data-internal-page="true"
Cheers!
I think I was having a similar problem. What I wanted to do was based on certain parameters, pop a dialog window on load (with that content on the same page), which they can close and view the page that loaded.
I could get it to pop on load using load, or the pageshow events, but when I clicked close that sent you back to the previous page in history, instead of just closing the dialog.
//target your 1st page content, here its id=success
//the modal content is in a page id=dialog and data-role="dialog"
$('#success').live('pageshow',function(){
window.setTimeout(function(){
$.mobile.changePage('#dialog','pop',false,false);
},1);
}
Its a hack, and just allows the page load to beat the dialog so it gets stuck in history. Then the default dialog close behavior for the dialog works as expected. Talk about a PITA, if they took a little more for the JQuery UI dialog it would have made things a ton easier.
And regarding your question: Have you looked at Jquery Mobile Actionsheet plugin
If you don't really require a page to be loaded, that should be ok.
Also helpful could be Cagintranet iPad popover, although you have to tweak the design to be fullscreen on mobile devices. If you require CSS/Jquery to do that let me know (I'm using this in a JQM plugin I'm writing)
Hope that helps.

Resources